packages feed

tricorder 1.0.0.0 → 1.1.0.0

raw patch · 108 files changed

+3066/−1916 lines, 108 filesdep +autodocodecdep ~atelier-coredep ~tricorder-typesnew-component:exe:helpPVP ok

version bump matches the API change (PVP)

Dependencies added: autodocodec

Dependency ranges changed: atelier-core, tricorder-types

API changes (from Hackage documentation)

- Tricorder.Build: BuildId :: Int -> BuildId
- Tricorder.Build: BuildProgress :: Int -> Int -> BuildProgress
- Tricorder.Build: BuildResult :: UTCTime -> Duration -> Int -> [Diagnostic] -> BuildResult
- Tricorder.Build: BuildState :: BuildPhase -> BuildId -> BuildState
- Tricorder.Build: Building :: [TestTarget] -> BuildProgress -> BuildPhase
- Tricorder.Build: Diagnostic :: Severity -> FilePath -> Int -> Int -> Int -> Int -> Text -> Text -> Diagnostic
- Tricorder.Build: Failed :: Text -> BuildPhase
- Tricorder.Build: Finished :: BuildResult -> PostBuild -> BuildPhase
- Tricorder.Build: PostBuild :: Suites -> Phase -> PostBuild
- Tricorder.Build: PostBuilding :: BuildResult -> PostBuild -> BuildPhase
- Tricorder.Build: SError :: Severity
- Tricorder.Build: SWarning :: Severity
- Tricorder.Build: Starting :: BuildPhase
- Tricorder.Build: [buildId] :: BuildState -> BuildId
- Tricorder.Build: [col] :: Diagnostic -> Int
- Tricorder.Build: [compiled] :: BuildProgress -> Int
- Tricorder.Build: [completedAt] :: BuildResult -> UTCTime
- Tricorder.Build: [diagnostics] :: BuildResult -> [Diagnostic]
- Tricorder.Build: [duration] :: BuildResult -> Duration
- Tricorder.Build: [endCol] :: Diagnostic -> Int
- Tricorder.Build: [endLine] :: Diagnostic -> Int
- Tricorder.Build: [evalComments] :: PostBuild -> Phase
- Tricorder.Build: [file] :: Diagnostic -> FilePath
- Tricorder.Build: [getBuildId] :: BuildId -> Int
- Tricorder.Build: [line] :: Diagnostic -> Int
- Tricorder.Build: [moduleCount] :: BuildResult -> Int
- Tricorder.Build: [phase] :: BuildState -> BuildPhase
- Tricorder.Build: [severity] :: Diagnostic -> Severity
- Tricorder.Build: [testSuites] :: PostBuild -> Suites
- Tricorder.Build: [text] :: Diagnostic -> Text
- Tricorder.Build: [title] :: Diagnostic -> Text
- Tricorder.Build: [total] :: BuildProgress -> Int
- Tricorder.Build: data BuildPhase
- Tricorder.Build: data BuildProgress
- Tricorder.Build: data BuildResult
- Tricorder.Build: data BuildState
- Tricorder.Build: data Diagnostic
- Tricorder.Build: data PostBuild
- Tricorder.Build: data Severity
- Tricorder.Build: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.BuildId
- Tricorder.Build: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.BuildPhase
- Tricorder.Build: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.BuildProgress
- Tricorder.Build: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.BuildResult
- Tricorder.Build: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.BuildState
- Tricorder.Build: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.Diagnostic
- Tricorder.Build: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.PostBuild
- Tricorder.Build: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.Severity
- Tricorder.Build: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.BuildId
- Tricorder.Build: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.BuildPhase
- Tricorder.Build: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.BuildProgress
- Tricorder.Build: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.BuildResult
- Tricorder.Build: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.BuildState
- Tricorder.Build: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.Diagnostic
- Tricorder.Build: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.PostBuild
- Tricorder.Build: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.Severity
- Tricorder.Build: instance GHC.Classes.Eq Tricorder.Build.BuildId
- Tricorder.Build: instance GHC.Classes.Eq Tricorder.Build.BuildPhase
- Tricorder.Build: instance GHC.Classes.Eq Tricorder.Build.BuildProgress
- Tricorder.Build: instance GHC.Classes.Eq Tricorder.Build.BuildResult
- Tricorder.Build: instance GHC.Classes.Eq Tricorder.Build.BuildState
- Tricorder.Build: instance GHC.Classes.Eq Tricorder.Build.Diagnostic
- Tricorder.Build: instance GHC.Classes.Eq Tricorder.Build.PostBuild
- Tricorder.Build: instance GHC.Classes.Eq Tricorder.Build.Severity
- Tricorder.Build: instance GHC.Classes.Ord Tricorder.Build.Severity
- Tricorder.Build: instance GHC.Generics.Generic Tricorder.Build.BuildPhase
- Tricorder.Build: instance GHC.Generics.Generic Tricorder.Build.BuildProgress
- Tricorder.Build: instance GHC.Generics.Generic Tricorder.Build.BuildResult
- Tricorder.Build: instance GHC.Generics.Generic Tricorder.Build.BuildState
- Tricorder.Build: instance GHC.Generics.Generic Tricorder.Build.Diagnostic
- Tricorder.Build: instance GHC.Generics.Generic Tricorder.Build.PostBuild
- Tricorder.Build: instance GHC.Num.Num Tricorder.Build.BuildId
- Tricorder.Build: instance GHC.Show.Show Tricorder.Build.BuildId
- Tricorder.Build: instance GHC.Show.Show Tricorder.Build.BuildPhase
- Tricorder.Build: instance GHC.Show.Show Tricorder.Build.BuildProgress
- Tricorder.Build: instance GHC.Show.Show Tricorder.Build.BuildResult
- Tricorder.Build: instance GHC.Show.Show Tricorder.Build.BuildState
- Tricorder.Build: instance GHC.Show.Show Tricorder.Build.Diagnostic
- Tricorder.Build: instance GHC.Show.Show Tricorder.Build.PostBuild
- Tricorder.Build: instance GHC.Show.Show Tricorder.Build.Severity
- Tricorder.Build: newtype BuildId
- Tricorder.Build.Changes: CabalChange :: ChangeKind
- Tricorder.Build.Changes: CabalChangeDetected :: FilePath -> Event -> CabalChangeDetected
- Tricorder.Build.Changes: data CabalChangeDetected
- Tricorder.Build.Changes: instance GHC.Classes.Eq Tricorder.Build.Changes.CabalChangeDetected
- Tricorder.Build.Changes: instance GHC.Show.Show Tricorder.Build.Changes.CabalChangeDetected
- Tricorder.Build.EvalComment: data Comments
- Tricorder.CLI.App.Test.Json: wrapResponse :: ToJSON a => Response a -> Either Text Text
- Tricorder.CLI.App.Test.Json.Responses: Error :: MessageWithLoc -> Response a
- Tricorder.CLI.App.Test.Json.Responses: MessageWithLoc :: Text -> Text -> MessageWithLoc
- Tricorder.CLI.App.Test.Json.Responses: Pending :: MessageWithLoc -> Response a
- Tricorder.CLI.App.Test.Json.Responses: Success :: a -> Response a
- Tricorder.CLI.App.Test.Json.Responses: SuitesResponse :: [Projection] -> SuitesResponse
- Tricorder.CLI.App.Test.Json.Responses: [location] :: MessageWithLoc -> Text
- Tricorder.CLI.App.Test.Json.Responses: [message] :: MessageWithLoc -> Text
- Tricorder.CLI.App.Test.Json.Responses: [suites] :: SuitesResponse -> [Projection]
- Tricorder.CLI.App.Test.Json.Responses: data MessageWithLoc
- Tricorder.CLI.App.Test.Json.Responses: data Response a
- Tricorder.CLI.App.Test.Json.Responses: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.CLI.App.Test.Json.Responses.MessageWithLoc
- Tricorder.CLI.App.Test.Json.Responses: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.CLI.App.Test.Json.Responses.MessageWithLoc
- Tricorder.CLI.App.Test.Json.Responses: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.CLI.App.Test.Json.Responses.SuitesResponse
- Tricorder.CLI.App.Test.Json.Responses: instance Data.Aeson.Types.ToJSON.ToJSON a => Data.Aeson.Types.ToJSON.ToJSON (Tricorder.CLI.App.Test.Json.Responses.Response a)
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Base.Applicative Tricorder.CLI.App.Test.Json.Responses.Response
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Base.Functor Tricorder.CLI.App.Test.Json.Responses.Response
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Base.Monad Tricorder.CLI.App.Test.Json.Responses.Response
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Classes.Eq Tricorder.CLI.App.Test.Json.Responses.MessageWithLoc
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Classes.Eq Tricorder.CLI.App.Test.Json.Responses.SuitesResponse
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Classes.Eq a => GHC.Classes.Eq (Tricorder.CLI.App.Test.Json.Responses.Response a)
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Generics.Generic (Tricorder.CLI.App.Test.Json.Responses.Response a)
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Generics.Generic Tricorder.CLI.App.Test.Json.Responses.MessageWithLoc
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Show.Show Tricorder.CLI.App.Test.Json.Responses.MessageWithLoc
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Show.Show Tricorder.CLI.App.Test.Json.Responses.SuitesResponse
- Tricorder.CLI.App.Test.Json.Responses: instance GHC.Show.Show a => GHC.Show.Show (Tricorder.CLI.App.Test.Json.Responses.Response a)
- Tricorder.CLI.App.Test.Json.Responses: newtype SuitesResponse
- Tricorder.Daemon.DaemonInfo: [targets] :: DaemonInfo -> [Target]
- Tricorder.Daemon.DaemonInfo: [watchDirs] :: DaemonInfo -> [FilePath]
- Tricorder.Daemon.DaemonInfo: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Daemon.DaemonInfo.DaemonInfo
- Tricorder.Daemon.DaemonInfo: instance GHC.Show.Show Tricorder.Daemon.DaemonInfo.DaemonInfo
- Tricorder.Daemon.DaemonInfo: runInput :: forall (es :: [Effect]) a. (Input Session :> es, Reader LogPath :> es, Reader ProjectRoot :> es, Reader SocketPath :> es) => Eff (Input DaemonInfo ': es) a -> Eff es a
- Tricorder.Daemon.Ghci.Result: toAbsolute :: FilePath -> FilePath -> FilePath
- Tricorder.Daemon.Ghci.Result: toRelative :: FilePath -> FilePath -> FilePath
- Tricorder.Daemon.Watch: isCabalFile :: FilePath -> Bool
- Tricorder.Logging: runLogging :: forall (es :: [Effect]) a. (Env :> es, File :> es, IOE :> es, Input LoadedConfig :> es, Reader LogPath :> es) => Eff (Log ': es) a -> Eff es a
- Tricorder.Runtime: LogPath :: FilePath -> LogPath
- Tricorder.Runtime: PidFile :: FilePath -> PidFile
- Tricorder.Runtime: ProjectRoot :: FilePath -> ProjectRoot
- Tricorder.Runtime: RuntimeDir :: FilePath -> RuntimeDir
- Tricorder.Runtime: SocketPath :: FilePath -> SocketPath
- Tricorder.Runtime: [getLogPath] :: LogPath -> FilePath
- Tricorder.Runtime: [getPidFile] :: PidFile -> FilePath
- Tricorder.Runtime: [getProjectRoot] :: ProjectRoot -> FilePath
- Tricorder.Runtime: [getRuntimeDir] :: RuntimeDir -> FilePath
- Tricorder.Runtime: [getSocketPath] :: SocketPath -> FilePath
- Tricorder.Runtime: newtype LogPath
- Tricorder.Runtime: newtype PidFile
- Tricorder.Runtime: newtype ProjectRoot
- Tricorder.Runtime: newtype RuntimeDir
- Tricorder.Runtime: newtype SocketPath
- Tricorder.Runtime: runLogPath :: forall (es :: [Effect]) a. Reader RuntimeDir :> es => Eff (Reader LogPath ': es) a -> Eff es a
- Tricorder.Runtime: runPidFile :: forall (es :: [Effect]) a. Reader RuntimeDir :> es => Eff (Reader PidFile ': es) a -> Eff es a
- Tricorder.Runtime: runProjectRoot :: forall (es :: [Effect]) a. (FileSystem :> es, HasCallStack) => Eff (Reader ProjectRoot ': es) a -> Eff es a
- Tricorder.Runtime: runRuntimeDir :: forall (es :: [Effect]) a. (FileSystem :> es, Reader ProjectRoot :> es) => Eff (Reader RuntimeDir ': es) a -> Eff es a
- Tricorder.Runtime: runRuntimeDirItem :: forall (es :: [Effect]) a b. Reader RuntimeDir :> es => FilePath -> (FilePath -> a) -> Eff (Reader a ': es) b -> Eff es b
- Tricorder.Runtime: runSocketPath :: forall (es :: [Effect]) a. Reader RuntimeDir :> es => Eff (Reader SocketPath ': es) a -> Eff es a
- Tricorder.Session.WatchExclusionPatterns: type Pattern = (Pattern, (GroupIndex, DoPa))
+ Tricorder.Build.ByteSize: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.ByteSize.ByteSize
+ Tricorder.Build.ByteSize: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.ByteSize.Unit
+ Tricorder.Build.Changes: ProjectChange :: ChangeKind
+ Tricorder.Build.Changes: ProjectChangeDetected :: Any -> Event -> ProjectChangeDetected
+ Tricorder.Build.Changes: data ProjectChangeDetected
+ Tricorder.Build.Changes: instance GHC.Classes.Eq Tricorder.Build.Changes.ProjectChangeDetected
+ Tricorder.Build.Changes: instance GHC.Show.Show Tricorder.Build.Changes.ProjectChangeDetected
+ Tricorder.Build.Diagnostic: Diagnostic :: Severity -> DiagnosticLocation -> Int -> Int -> Int -> Int -> Text -> Text -> Diagnostic
+ Tricorder.Build.Diagnostic: [col] :: Diagnostic -> Int
+ Tricorder.Build.Diagnostic: [endCol] :: Diagnostic -> Int
+ Tricorder.Build.Diagnostic: [endLine] :: Diagnostic -> Int
+ Tricorder.Build.Diagnostic: [file] :: Diagnostic -> DiagnosticLocation
+ Tricorder.Build.Diagnostic: [line] :: Diagnostic -> Int
+ Tricorder.Build.Diagnostic: [severity] :: Diagnostic -> Severity
+ Tricorder.Build.Diagnostic: [text] :: Diagnostic -> Text
+ Tricorder.Build.Diagnostic: [title] :: Diagnostic -> Text
+ Tricorder.Build.Diagnostic: data Diagnostic
+ Tricorder.Build.Diagnostic: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.Diagnostic.Diagnostic
+ Tricorder.Build.Diagnostic: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.Diagnostic.Diagnostic
+ Tricorder.Build.Diagnostic: instance GHC.Classes.Eq Tricorder.Build.Diagnostic.Diagnostic
+ Tricorder.Build.Diagnostic: instance GHC.Generics.Generic Tricorder.Build.Diagnostic.Diagnostic
+ Tricorder.Build.Diagnostic: instance GHC.Show.Show Tricorder.Build.Diagnostic.Diagnostic
+ Tricorder.Build.DiagnosticLocation: Location :: Any -> DiagnosticLocation
+ Tricorder.Build.DiagnosticLocation: Locationless :: DiagnosticLocation
+ Tricorder.Build.DiagnosticLocation: data DiagnosticLocation
+ Tricorder.Build.DiagnosticLocation: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.DiagnosticLocation.DiagnosticLocation
+ Tricorder.Build.DiagnosticLocation: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.DiagnosticLocation.DiagnosticLocation
+ Tricorder.Build.DiagnosticLocation: instance GHC.Classes.Eq Tricorder.Build.DiagnosticLocation.DiagnosticLocation
+ Tricorder.Build.DiagnosticLocation: instance GHC.Classes.Ord Tricorder.Build.DiagnosticLocation.DiagnosticLocation
+ Tricorder.Build.DiagnosticLocation: instance GHC.Generics.Generic Tricorder.Build.DiagnosticLocation.DiagnosticLocation
+ Tricorder.Build.DiagnosticLocation: instance GHC.Show.Show Tricorder.Build.DiagnosticLocation.DiagnosticLocation
+ Tricorder.Build.DiagnosticLocation: instance Relude.String.Conversion.ToText Tricorder.Build.DiagnosticLocation.DiagnosticLocation
+ Tricorder.Build.DiagnosticLocation: map :: (Any -> Any) -> DiagnosticLocation -> DiagnosticLocation
+ Tricorder.Build.EvalComment: newtype Comments
+ Tricorder.Build.Id: Id :: Int -> Id
+ Tricorder.Build.Id: [getId] :: Id -> Int
+ Tricorder.Build.Id: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.Id.Id
+ Tricorder.Build.Id: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.Id.Id
+ Tricorder.Build.Id: instance GHC.Classes.Eq Tricorder.Build.Id.Id
+ Tricorder.Build.Id: instance GHC.Num.Num Tricorder.Build.Id.Id
+ Tricorder.Build.Id: instance GHC.Show.Show Tricorder.Build.Id.Id
+ Tricorder.Build.Id: newtype Id
+ Tricorder.Build.Phase: Building :: [TestTarget] -> Progress -> Phase
+ Tricorder.Build.Phase: Failed :: Text -> Phase
+ Tricorder.Build.Phase: Finished :: Result -> PostBuild -> Phase
+ Tricorder.Build.Phase: PostBuilding :: Result -> PostBuild -> Phase
+ Tricorder.Build.Phase: Starting :: Phase
+ Tricorder.Build.Phase: data Phase
+ Tricorder.Build.Phase: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.Phase.Phase
+ Tricorder.Build.Phase: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.Phase.Phase
+ Tricorder.Build.Phase: instance GHC.Classes.Eq Tricorder.Build.Phase.Phase
+ Tricorder.Build.Phase: instance GHC.Generics.Generic Tricorder.Build.Phase.Phase
+ Tricorder.Build.Phase: instance GHC.Show.Show Tricorder.Build.Phase.Phase
+ Tricorder.Build.PostBuild: PostBuild :: Suites -> Phase -> PostBuild
+ Tricorder.Build.PostBuild: [evalComments] :: PostBuild -> Phase
+ Tricorder.Build.PostBuild: [testSuites] :: PostBuild -> Suites
+ Tricorder.Build.PostBuild: data PostBuild
+ Tricorder.Build.PostBuild: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.PostBuild.PostBuild
+ Tricorder.Build.PostBuild: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.PostBuild.PostBuild
+ Tricorder.Build.PostBuild: instance GHC.Classes.Eq Tricorder.Build.PostBuild.PostBuild
+ Tricorder.Build.PostBuild: instance GHC.Generics.Generic Tricorder.Build.PostBuild.PostBuild
+ Tricorder.Build.PostBuild: instance GHC.Show.Show Tricorder.Build.PostBuild.PostBuild
+ Tricorder.Build.Progress: Progress :: Int -> Int -> Progress
+ Tricorder.Build.Progress: [compiled] :: Progress -> Int
+ Tricorder.Build.Progress: [total] :: Progress -> Int
+ Tricorder.Build.Progress: data Progress
+ Tricorder.Build.Progress: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.Progress.Progress
+ Tricorder.Build.Progress: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.Progress.Progress
+ Tricorder.Build.Progress: instance GHC.Classes.Eq Tricorder.Build.Progress.Progress
+ Tricorder.Build.Progress: instance GHC.Generics.Generic Tricorder.Build.Progress.Progress
+ Tricorder.Build.Progress: instance GHC.Show.Show Tricorder.Build.Progress.Progress
+ Tricorder.Build.Result: Result :: UTCTime -> Duration -> Int -> [Diagnostic] -> Result
+ Tricorder.Build.Result: [completedAt] :: Result -> UTCTime
+ Tricorder.Build.Result: [diagnostics] :: Result -> [Diagnostic]
+ Tricorder.Build.Result: [duration] :: Result -> Duration
+ Tricorder.Build.Result: [moduleCount] :: Result -> Int
+ Tricorder.Build.Result: data Result
+ Tricorder.Build.Result: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.Result.Result
+ Tricorder.Build.Result: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.Result.Result
+ Tricorder.Build.Result: instance GHC.Classes.Eq Tricorder.Build.Result.Result
+ Tricorder.Build.Result: instance GHC.Generics.Generic Tricorder.Build.Result.Result
+ Tricorder.Build.Result: instance GHC.Show.Show Tricorder.Build.Result.Result
+ Tricorder.Build.Severity: Error :: Severity
+ Tricorder.Build.Severity: Warning :: Severity
+ Tricorder.Build.Severity: data Severity
+ Tricorder.Build.Severity: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.Severity.Severity
+ Tricorder.Build.Severity: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.Severity.Severity
+ Tricorder.Build.Severity: instance GHC.Classes.Eq Tricorder.Build.Severity.Severity
+ Tricorder.Build.Severity: instance GHC.Classes.Ord Tricorder.Build.Severity.Severity
+ Tricorder.Build.Severity: instance GHC.Show.Show Tricorder.Build.Severity.Severity
+ Tricorder.Build.State: State :: Phase -> Id -> State
+ Tricorder.Build.State: [buildId] :: State -> Id
+ Tricorder.Build.State: [phase] :: State -> Phase
+ Tricorder.Build.State: data State
+ Tricorder.Build.State: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Build.State.State
+ Tricorder.Build.State: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Build.State.State
+ Tricorder.Build.State: instance GHC.Classes.Eq Tricorder.Build.State.State
+ Tricorder.Build.State: instance GHC.Generics.Generic Tricorder.Build.State.State
+ Tricorder.Build.State: instance GHC.Show.Show Tricorder.Build.State.State
+ Tricorder.CLI.App.Test.Json: wrapSuites :: Schema -> Response (SuitesResponse Projection) -> Either Text Text
+ Tricorder.CLI.Arguments: opts :: ParserInfo Command
+ Tricorder.CLI.Docs: renderReference :: Text
+ Tricorder.Daemon.DaemonInfo: [projectRoot] :: DaemonInfo -> ProjectRoot
+ Tricorder.Daemon.DaemonInfo: [session] :: DaemonInfo -> Session
+ Tricorder.Daemon.DaemonInfo: asInput :: forall (es :: [Effect]) a. (Input Session :> es, Reader LogPath :> es, Reader ProjectRoot :> es, Reader SocketPath :> es) => Eff (Input DaemonInfo ': es) a -> Eff es a
+ Tricorder.Daemon.Dispatch: planActions :: [DispatchAction] -> [DispatchAction]
+ Tricorder.Daemon.Ghci.Config: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Daemon.Ghci.Config.Config
+ Tricorder.Daemon.Ghci.Config: instance GHC.Generics.Generic Tricorder.Daemon.Ghci.Config.Config
+ Tricorder.Daemon.Watch: isProjectFile :: Path path => path -> Bool
+ Tricorder.Logging: run :: forall (es :: [Effect]) a. (Env :> es, FileSystem :> es, Handles :> es, IOE :> es, Input LoadedConfig :> es, Reader LogPath :> es) => Eff (Log ': es) a -> Eff es a
+ Tricorder.Runtime.Cache: Cache :: Absolute -> Cache
+ Tricorder.Runtime.Cache: [getCache] :: Cache -> Absolute
+ Tricorder.Runtime.Cache: asReader :: forall (es :: [Effect]) a. (Env :> es, Exit :> es, FileSystem :> es, Reader ProjectHash :> es) => Eff (Reader Cache ': es) a -> Eff es a
+ Tricorder.Runtime.Cache: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Runtime.Cache.Cache
+ Tricorder.Runtime.Cache: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Runtime.Cache.Cache
+ Tricorder.Runtime.Cache: instance GHC.Classes.Eq Tricorder.Runtime.Cache.Cache
+ Tricorder.Runtime.Cache: instance GHC.Generics.Generic Tricorder.Runtime.Cache.Cache
+ Tricorder.Runtime.Cache: instance GHC.Show.Show Tricorder.Runtime.Cache.Cache
+ Tricorder.Runtime.Cache: newtype Cache
+ Tricorder.Runtime.Directory: Directory :: Absolute -> Directory
+ Tricorder.Runtime.Directory: [getDirectory] :: Directory -> Absolute
+ Tricorder.Runtime.Directory: asReader :: forall (es :: [Effect]) a. (Env :> es, Exit :> es, FileSystem :> es, Log :> es, Reader ProjectHash :> es) => Eff (Reader Directory ': es) a -> Eff es a
+ Tricorder.Runtime.Directory: asReaderFor :: forall (es :: [Effect]) a b. Reader Directory :> es => Relative -> (Absolute -> a) -> Eff (Reader a ': es) b -> Eff es b
+ Tricorder.Runtime.Directory: newtype Directory
+ Tricorder.Runtime.LogPath: LogPath :: Absolute -> LogPath
+ Tricorder.Runtime.LogPath: [getLogPath] :: LogPath -> Absolute
+ Tricorder.Runtime.LogPath: asReader :: forall (es :: [Effect]) a. (Env :> es, Reader Cache :> es) => Eff (Reader LogPath ': es) a -> Eff es a
+ Tricorder.Runtime.LogPath: envName :: String
+ Tricorder.Runtime.LogPath: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Runtime.LogPath.LogPath
+ Tricorder.Runtime.LogPath: instance GHC.Classes.Eq Tricorder.Runtime.LogPath.LogPath
+ Tricorder.Runtime.LogPath: instance GHC.Generics.Generic Tricorder.Runtime.LogPath.LogPath
+ Tricorder.Runtime.LogPath: instance GHC.Show.Show Tricorder.Runtime.LogPath.LogPath
+ Tricorder.Runtime.LogPath: newtype LogPath
+ Tricorder.Runtime.PidFile: PidFile :: Absolute -> PidFile
+ Tricorder.Runtime.PidFile: [getPidFile] :: PidFile -> Absolute
+ Tricorder.Runtime.PidFile: asReader :: forall (es :: [Effect]) a. Reader Directory :> es => Eff (Reader PidFile ': es) a -> Eff es a
+ Tricorder.Runtime.PidFile: newtype PidFile
+ Tricorder.Runtime.ProjectHash: ProjectHash :: Relative -> ProjectHash
+ Tricorder.Runtime.ProjectHash: [getProjectHash] :: ProjectHash -> Relative
+ Tricorder.Runtime.ProjectHash: asReader :: forall (es :: [Effect]) a. (FileSystem :> es, Reader ProjectRoot :> es) => Eff (Reader ProjectHash ': es) a -> Eff es a
+ Tricorder.Runtime.ProjectHash: instance Data.Aeson.Types.FromJSON.FromJSON Tricorder.Runtime.ProjectHash.ProjectHash
+ Tricorder.Runtime.ProjectHash: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Runtime.ProjectHash.ProjectHash
+ Tricorder.Runtime.ProjectHash: instance GHC.Classes.Eq Tricorder.Runtime.ProjectHash.ProjectHash
+ Tricorder.Runtime.ProjectHash: instance GHC.Generics.Generic Tricorder.Runtime.ProjectHash.ProjectHash
+ Tricorder.Runtime.ProjectHash: instance GHC.Show.Show Tricorder.Runtime.ProjectHash.ProjectHash
+ Tricorder.Runtime.ProjectHash: newtype ProjectHash
+ Tricorder.Runtime.ProjectRoot: ProjectRoot :: Absolute -> ProjectRoot
+ Tricorder.Runtime.ProjectRoot: [getProjectRoot] :: ProjectRoot -> Absolute
+ Tricorder.Runtime.ProjectRoot: asReader :: forall (es :: [Effect]) a. (FileSystem :> es, HasCallStack) => Eff (Reader ProjectRoot ': es) a -> Eff es a
+ Tricorder.Runtime.ProjectRoot: findFileUpwards :: forall (es :: [Effect]). FileSystem :> es => Relative -> Absolute -> Eff es (Maybe Absolute)
+ Tricorder.Runtime.ProjectRoot: findProjectRoot :: forall (es :: [Effect]). FileSystem :> es => Absolute -> Eff es (Maybe Absolute)
+ Tricorder.Runtime.ProjectRoot: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Runtime.ProjectRoot.ProjectRoot
+ Tricorder.Runtime.ProjectRoot: instance GHC.Classes.Eq Tricorder.Runtime.ProjectRoot.ProjectRoot
+ Tricorder.Runtime.ProjectRoot: newtype ProjectRoot
+ Tricorder.Runtime.SocketPath: SocketPath :: Absolute -> SocketPath
+ Tricorder.Runtime.SocketPath: [getSocketPath] :: SocketPath -> Absolute
+ Tricorder.Runtime.SocketPath: asReader :: forall (es :: [Effect]) a. Reader Directory :> es => Eff (Reader SocketPath ': es) a -> Eff es a
+ Tricorder.Runtime.SocketPath: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Runtime.SocketPath.SocketPath
+ Tricorder.Runtime.SocketPath: instance GHC.Classes.Eq Tricorder.Runtime.SocketPath.SocketPath
+ Tricorder.Runtime.SocketPath: instance GHC.Generics.Generic Tricorder.Runtime.SocketPath.SocketPath
+ Tricorder.Runtime.SocketPath: instance GHC.Show.Show Tricorder.Runtime.SocketPath.SocketPath
+ Tricorder.Runtime.SocketPath: newtype SocketPath
+ Tricorder.Session: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Session.Session
+ Tricorder.Session: instance GHC.Generics.Generic Tricorder.Session.Session
+ Tricorder.Session.CommandTemplate: instance Data.Aeson.Types.ToJSON.ToJSON (Tricorder.Session.CommandTemplate.CommandTemplate stage)
+ Tricorder.Session.Repl: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Session.Repl.Repl
+ Tricorder.Session.Stage.Build.Session: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Session.Stage.Build.Session.Session
+ Tricorder.Session.Stage.Build.Session: instance GHC.Generics.Generic Tricorder.Session.Stage.Build.Session.Session
+ Tricorder.Session.Stage.Eval.Session: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Session.Stage.Eval.Session.Session
+ Tricorder.Session.Stage.Eval.Session: instance GHC.Generics.Generic Tricorder.Session.Stage.Eval.Session.Session
+ Tricorder.Session.Stage.Test.Session: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Session.Stage.Test.Session.ResolvedTestOptions
+ Tricorder.Session.Stage.Test.Session: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Session.Stage.Test.Session.Session
+ Tricorder.Session.Stage.Test.Session: instance GHC.Generics.Generic Tricorder.Session.Stage.Test.Session.ResolvedTestOptions
+ Tricorder.Session.Stage.Test.Session: instance GHC.Generics.Generic Tricorder.Session.Stage.Test.Session.Session
+ Tricorder.Session.WatchExclusionPatterns: Pattern :: (Pattern, (GroupIndex, DoPa)) -> Pattern
+ Tricorder.Session.WatchExclusionPatterns: [getPattern] :: Pattern -> (Pattern, (GroupIndex, DoPa))
+ Tricorder.Session.WatchExclusionPatterns: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Session.WatchExclusionPatterns.Pattern
+ Tricorder.Session.WatchExclusionPatterns: instance Data.Aeson.Types.ToJSON.ToJSON Tricorder.Session.WatchExclusionPatterns.WatchExclusionPatterns
+ Tricorder.Session.WatchExclusionPatterns: instance GHC.Classes.Eq Tricorder.Session.WatchExclusionPatterns.Pattern
+ Tricorder.Session.WatchExclusionPatterns: instance GHC.Show.Show Tricorder.Session.WatchExclusionPatterns.Pattern
+ Tricorder.Session.WatchExclusionPatterns: newtype Pattern
+ Tricorder.SourceLookup.Tarball: TarballAddFailed :: TarballOutcome
- Tricorder.Build.Changes: SourceChangeDetected :: FilePath -> Event -> SourceChangeDetected
+ Tricorder.Build.Changes: SourceChangeDetected :: Any -> Event -> SourceChangeDetected
- Tricorder.Build.EvalComment: Evaluation :: FilePath -> Comment -> State -> Evaluation
+ Tricorder.Build.EvalComment: Evaluation :: Relative -> Comment -> State -> Evaluation
- Tricorder.Build.EvalComment: [file] :: Evaluation -> FilePath
+ Tricorder.Build.EvalComment: [file] :: Evaluation -> Relative
- Tricorder.CLI.App: run :: forall (es :: [Effect]). (Brick :> es, BrickChan :> es, Clock :> es, Conc :> es, Concurrent :> es, Console :> es, Daemons :> es, Delay :> es, Exit :> es, File :> es, FileSystem :> es, GhcPkg :> es, Hackage :> es, IOE :> es, Input Session :> es, Input DaemonInfo :> es, Input [CabalFile] :> es, Log :> es, PackageStore :> es, Process :> es, Provider_ Console Output :> es, Reader Command :> es, Reader Config :> es, Reader LogPath :> es, Reader PidFile :> es, Reader SocketPath :> es, Timeout :> es, UnixSocket :> es) => Eff es ()
+ Tricorder.CLI.App: run :: forall (es :: [Effect]). (Brick :> es, BrickChan :> es, Clock :> es, Conc :> es, Concurrent :> es, Console :> es, Daemons :> es, Delay :> es, Exit :> es, FileSystem :> es, GhcPkg :> es, Hackage :> es, Handles :> es, IOE :> es, Input Session :> es, Input DaemonInfo :> es, Input [CabalFile] :> es, Log :> es, PackageStore :> es, Process :> es, Provider_ Console Output :> es, Reader Command :> es, Reader Config :> es, Reader LogPath :> es, Reader PidFile :> es, Reader SocketPath :> es, Timeout :> es, UnixSocket :> es) => Eff es ()
- Tricorder.CLI.App.Daemon: run :: forall (es :: [Effect]). (Console :> es, Daemons :> es, Delay :> es, File :> es, IOE :> es, Input DaemonInfo :> es, Reader PidFile :> es, Reader SocketPath :> es, Timeout :> es, UnixSocket :> es) => Command -> Eff es ()
+ Tricorder.CLI.App.Daemon: run :: forall (es :: [Effect]). (Console :> es, Daemons :> es, Delay :> es, Handles :> es, IOE :> es, Input DaemonInfo :> es, Reader PidFile :> es, Reader SocketPath :> es, Timeout :> es, UnixSocket :> es) => Command -> Eff es ()
- Tricorder.CLI.App.Test: run :: forall (es :: [Effect]). (Console :> es, Daemons :> es, Delay :> es, Exit :> es, File :> es, IOE :> es, Reader PidFile :> es, Reader SocketPath :> es, UnixSocket :> es) => Command -> Eff es ()
+ Tricorder.CLI.App.Test: run :: forall (es :: [Effect]). (Console :> es, Daemons :> es, Delay :> es, Exit :> es, Handles :> es, IOE :> es, Reader PidFile :> es, Reader SocketPath :> es, UnixSocket :> es) => Command -> Eff es ()
- Tricorder.CLI.App.Test.Json: showBasePhase :: Either Text BuildState -> (Suites -> Response a) -> Response a
+ Tricorder.CLI.App.Test.Json: showBasePhase :: Either Text State -> (Suites -> Response a) -> Response a
- Tricorder.CLI.App.Test.Json: showSuites :: [TestTarget] -> TestFilter -> Schema -> Suites -> Response SuitesResponse
+ Tricorder.CLI.App.Test.Json: showSuites :: [TestTarget] -> TestFilter -> Schema -> Suites -> Response (SuitesResponse Projection)
- Tricorder.CLI.App.Test.Text: showBasePhase :: (Suites -> Either Text Text) -> BuildPhase -> Either Text Text
+ Tricorder.CLI.App.Test.Text: showBasePhase :: (Suites -> Either Text Text) -> Phase -> Either Text Text
- Tricorder.CLI.App.Test.Text: wrapTextShow :: Either Text BuildState -> (BuildPhase -> Either Text Text) -> Either Text Text
+ Tricorder.CLI.App.Test.Text: wrapTextShow :: Either Text State -> (Phase -> Either Text Text) -> Either Text Text
- Tricorder.CLI.Daemon: restartDaemon :: forall (es :: [Effect]). (Daemons :> es, Delay :> es, File :> es, IOE :> es, Reader PidFile :> es, Reader SocketPath :> es, Timeout :> es, UnixSocket :> es) => IfThereArePendingQueries -> Eff es (Maybe (Either [Text] Text))
+ Tricorder.CLI.Daemon: restartDaemon :: forall (es :: [Effect]). (Daemons :> es, Delay :> es, Handles :> es, IOE :> es, Reader PidFile :> es, Reader SocketPath :> es, Timeout :> es, UnixSocket :> es) => IfThereArePendingQueries -> Eff es (Maybe (Either [Text] Text))
- Tricorder.CLI.Daemon: stopDaemon :: forall (es :: [Effect]). (Daemons :> es, Delay :> es, File :> es, Reader PidFile :> es, Reader SocketPath :> es, Timeout :> es, UnixSocket :> es) => IfThereArePendingQueries -> Eff es (Either [Text] Text)
+ Tricorder.CLI.Daemon: stopDaemon :: forall (es :: [Effect]). (Daemons :> es, Delay :> es, Handles :> es, Reader PidFile :> es, Reader SocketPath :> es, Timeout :> es, UnixSocket :> es) => IfThereArePendingQueries -> Eff es (Either [Text] Text)
- Tricorder.CLI.Operations: showEvalComments :: forall (es :: [Effect]). (Console :> es, Exit :> es, File :> es, Reader SocketPath :> es, UnixSocket :> es) => EvalCommentsOptions -> Eff es ()
+ Tricorder.CLI.Operations: showEvalComments :: forall (es :: [Effect]). (Console :> es, Exit :> es, Handles :> es, Reader SocketPath :> es, UnixSocket :> es) => EvalCommentsOptions -> Eff es ()
- Tricorder.CLI.Operations: showLog :: forall (es :: [Effect]). (Console :> es, FileSystem :> es) => FilePath -> Eff es ()
+ Tricorder.CLI.Operations: showLog :: forall (es :: [Effect]). (Console :> es, FileSystem :> es) => Absolute -> Eff es ()
- Tricorder.CLI.Operations: showStatus :: forall (es :: [Effect]). (Clock :> es, Console :> es, Exit :> es, File :> es, Provider_ Console Output :> es, Reader SocketPath :> es, UnixSocket :> es) => StatusOptions -> Eff es ()
+ Tricorder.CLI.Operations: showStatus :: forall (es :: [Effect]). (Clock :> es, Console :> es, Exit :> es, Handles :> es, Provider_ Console Output :> es, Reader SocketPath :> es, UnixSocket :> es) => StatusOptions -> Eff es ()
- Tricorder.CLI.UI: viewUi :: forall (es :: [Effect]). (Brick :> es, BrickChan :> es, Clock :> es, Conc :> es, Concurrent :> es, Console :> es, Delay :> es, Exit :> es, File :> es, Process :> es, Reader Config :> es, Reader SocketPath :> es, UnixSocket :> es) => Eff es ()
+ Tricorder.CLI.UI: viewUi :: forall (es :: [Effect]). (Brick :> es, BrickChan :> es, Clock :> es, Conc :> es, Concurrent :> es, Console :> es, Delay :> es, Exit :> es, Handles :> es, Process :> es, Reader Config :> es, Reader SocketPath :> es, UnixSocket :> es) => Eff es ()
- Tricorder.CLI.UI.Event: NewBuildState :: Either Restarting BuildState -> Event
+ Tricorder.CLI.UI.Event: NewBuildState :: Either Restarting State -> Event
- Tricorder.CLI.UI.State: State :: Processed Text BuildState -> TimeZone -> Route -> TestFilter -> Bool -> State
+ Tricorder.CLI.UI.State: State :: Processed Text State -> TimeZone -> Route -> TestFilter -> Bool -> State
- Tricorder.CLI.UI.State: [buildState] :: State -> Processed Text BuildState
+ Tricorder.CLI.UI.State: [buildState] :: State -> Processed Text State
- Tricorder.Config.LoadedConfig: configFileName :: FilePath
+ Tricorder.Config.LoadedConfig: configFileName :: Relative
- Tricorder.Daemon.Builder: [Consider] :: forall (a :: Type -> Type). FilePath -> Event -> Builder a BuildConsideration
+ Tricorder.Daemon.Builder: [Consider] :: forall (a :: Type -> Type). Any -> Event -> Builder a BuildConsideration
- Tricorder.Daemon.Builder: compileBuildResults :: ProjectRoot -> WatchDirs -> DiagnosticMap -> NewLoadResult -> (DiagnosticMap, BuildResult)
+ Tricorder.Daemon.Builder: compileBuildResults :: ProjectRoot -> WatchDirs -> DiagnosticMap -> NewLoadResult -> (DiagnosticMap, Result)
- Tricorder.Daemon.Builder: consider :: forall (es :: [Effect]). (HasCallStack, Builder :> es) => FilePath -> Event -> Eff es BuildConsideration
+ Tricorder.Daemon.Builder: consider :: forall (es :: [Effect]). (HasCallStack, Builder :> es) => Any -> Event -> Eff es BuildConsideration
- Tricorder.Daemon.Builder: with :: forall (es :: [Effect]) a. (Clock :> es, Session :> es, Log :> es, Pub BuildProgress :> es, Reader ProjectRoot :> es) => BuildId -> RenderedCommand 'Build -> WatchDirs -> (BuilderState -> NewLoadResult -> Eff (Builder ': es) a) -> Eff es (Either SomeException a)
+ Tricorder.Daemon.Builder: with :: forall (es :: [Effect]) a. (Clock :> es, Session :> es, Log :> es, Pub Progress :> es, Reader ProjectRoot :> es) => Id -> RenderedCommand 'Build -> WatchDirs -> (BuilderState -> NewLoadResult -> Eff (Builder ': es) a) -> Eff es (Either SomeException a)
- Tricorder.Daemon.Core: main :: forall (es :: [Effect]). (Chan :> es, Clock :> es, Conc :> es, Concurrent :> es, EvalCommentRunner :> es, Session :> es, Log :> es, Process :> es, Pub BuildPhase :> es, Reader ProjectRoot :> es, State BuildId :> es, Sub CabalChangeDetected :> es, Sub SourceChangeDetected :> es, TestRunner :> es, Waiters :> es) => Session -> Eff es Void
+ Tricorder.Daemon.Core: main :: forall (es :: [Effect]). (Chan :> es, Clock :> es, Conc :> es, Concurrent :> es, EvalCommentRunner :> es, Session :> es, Log :> es, Process :> es, Pub Phase :> es, Reader ProjectRoot :> es, State Id :> es, Sub ProjectChangeDetected :> es, Sub SourceChangeDetected :> es, TestRunner :> es, Waiters :> es) => Session -> Eff es Void
- Tricorder.Daemon.DaemonInfo: DaemonInfo :: [Target] -> [FilePath] -> FilePath -> FilePath -> DaemonInfo
+ Tricorder.Daemon.DaemonInfo: DaemonInfo :: Session -> SocketPath -> LogPath -> ProjectRoot -> DaemonInfo
- Tricorder.Daemon.DaemonInfo: [logFile] :: DaemonInfo -> FilePath
+ Tricorder.Daemon.DaemonInfo: [logFile] :: DaemonInfo -> LogPath
- Tricorder.Daemon.DaemonInfo: [sockPath] :: DaemonInfo -> FilePath
+ Tricorder.Daemon.DaemonInfo: [sockPath] :: DaemonInfo -> SocketPath
- Tricorder.Daemon.Dispatch: Add :: FilePath -> DispatchAction
+ Tricorder.Daemon.Dispatch: Add :: Any -> DispatchAction
- Tricorder.Daemon.Dispatch: BuilderState :: Map FilePath LoadedModule -> KnownTargetNames -> DiagnosticMap -> BuilderState
+ Tricorder.Daemon.Dispatch: BuilderState :: Map Any LoadedModule -> KnownTargetNames -> DiagnosticMap -> BuilderState
- Tricorder.Daemon.Dispatch: [loadedModules] :: BuilderState -> Map FilePath LoadedModule
+ Tricorder.Daemon.Dispatch: [loadedModules] :: BuilderState -> Map Any LoadedModule
- Tricorder.Daemon.Dispatch: dispatch :: KnownTargetNames -> Maybe LoadedModule -> FilePath -> Event -> Maybe DispatchAction
+ Tricorder.Daemon.Dispatch: dispatch :: KnownTargetNames -> Maybe LoadedModule -> Any -> Event -> Maybe DispatchAction
- Tricorder.Daemon.Dispatch: fileMatchesAnyTarget :: KnownTargetNames -> FilePath -> Bool
+ Tricorder.Daemon.Dispatch: fileMatchesAnyTarget :: Path path => KnownTargetNames -> path -> Bool
- Tricorder.Daemon.Dispatch: filterToWatchDirs :: FilePath -> WatchDirs -> [Diagnostic] -> [Diagnostic]
+ Tricorder.Daemon.Dispatch: filterToWatchDirs :: Absolute -> WatchDirs -> [Diagnostic] -> [Diagnostic]
- Tricorder.Daemon.Dispatch: type DiagnosticMap = Map FilePath [Diagnostic]
+ Tricorder.Daemon.Dispatch: type DiagnosticMap = Map DiagnosticLocation [Diagnostic]
- Tricorder.Daemon.EvalCommentRunner: [FindEvalCommentsInModules] :: forall (a :: Type -> Type). Map FilePath LoadedModule -> EvalCommentRunner a [(LoadedModule, NonEmpty Comment)]
+ Tricorder.Daemon.EvalCommentRunner: [FindEvalCommentsInModules] :: forall (a :: Type -> Type). Map Any LoadedModule -> EvalCommentRunner a [(LoadedModule, NonEmpty Comment)]
- Tricorder.Daemon.EvalCommentRunner: findEvalCommentsInModules :: forall (es :: [Effect]). (HasCallStack, EvalCommentRunner :> es) => Map FilePath LoadedModule -> Eff es [(LoadedModule, NonEmpty Comment)]
+ Tricorder.Daemon.EvalCommentRunner: findEvalCommentsInModules :: forall (es :: [Effect]). (HasCallStack, EvalCommentRunner :> es) => Map Any LoadedModule -> Eff es [(LoadedModule, NonEmpty Comment)]
- Tricorder.Daemon.EvalCommentRunner: run :: forall (es :: [Effect]) a. (Conc :> es, Concurrent :> es, File :> es, FileSystem :> es, Log :> es, Process :> es, Reader ProjectRoot :> es, Timeout :> es) => Eff (EvalCommentRunner ': es) a -> Eff es a
+ Tricorder.Daemon.EvalCommentRunner: run :: forall (es :: [Effect]) a. (Conc :> es, Concurrent :> es, FileSystem :> es, Handles :> es, Log :> es, Process :> es, Reader ProjectRoot :> es, Timeout :> es) => Eff (EvalCommentRunner ': es) a -> Eff es a
- Tricorder.Daemon.Ghci.Config: Config :: Second -> Second -> [Text] -> Config
+ Tricorder.Daemon.Ghci.Config: Config :: AsRawUnit Second -> AsRawUnit Second -> [Text] -> Config
- Tricorder.Daemon.Ghci.Config: [shutdownTimeout] :: Config -> Second
+ Tricorder.Daemon.Ghci.Config: [shutdownTimeout] :: Config -> AsRawUnit Second
- Tricorder.Daemon.Ghci.Config: [startupTimeout] :: Config -> Second
+ Tricorder.Daemon.Ghci.Config: [startupTimeout] :: Config -> AsRawUnit Second
- Tricorder.Daemon.Ghci.Controls: Controls :: m LoadResult -> m () -> (FilePath -> m LoadResult) -> (Text -> m LoadResult) -> Controls (m :: Type -> Type)
+ Tricorder.Daemon.Ghci.Controls: Controls :: m LoadResult -> m () -> (Any -> m LoadResult) -> (Text -> m LoadResult) -> Controls (m :: Type -> Type)
- Tricorder.Daemon.Ghci.Controls: [add] :: Controls (m :: Type -> Type) -> FilePath -> m LoadResult
+ Tricorder.Daemon.Ghci.Controls: [add] :: Controls (m :: Type -> Type) -> Any -> m LoadResult
- Tricorder.Daemon.Ghci.Diagnostic: headerParser :: TextParser (Text, Position, Position, Text)
+ Tricorder.Daemon.Ghci.Diagnostic: headerParser :: TextParser (Any, Position, Position, Text)
- Tricorder.Daemon.Ghci.LoadResult: LoadResult :: Int -> Set FilePath -> Map FilePath LoadedModule -> [Text] -> [Diagnostic] -> LoadResult
+ Tricorder.Daemon.Ghci.LoadResult: LoadResult :: Int -> Set Any -> Map Any LoadedModule -> [Text] -> [Diagnostic] -> LoadResult
- Tricorder.Daemon.Ghci.LoadResult: [compiledFiles] :: LoadResult -> Set FilePath
+ Tricorder.Daemon.Ghci.LoadResult: [compiledFiles] :: LoadResult -> Set Any
- Tricorder.Daemon.Ghci.LoadResult: [loadedModules] :: LoadResult -> Map FilePath LoadedModule
+ Tricorder.Daemon.Ghci.LoadResult: [loadedModules] :: LoadResult -> Map Any LoadedModule
- Tricorder.Daemon.Ghci.LoadResult: resolveKnownTargets :: Map FilePath LoadedModule -> LoadResult -> Map FilePath LoadedModule
+ Tricorder.Daemon.Ghci.LoadResult: resolveKnownTargets :: Map Any LoadedModule -> LoadResult -> Map Any LoadedModule
- Tricorder.Daemon.Ghci.LoadedModule: LoadedModule :: FilePath -> Text -> LoadedModule
+ Tricorder.Daemon.Ghci.LoadedModule: LoadedModule :: Relative -> Text -> LoadedModule
- Tricorder.Daemon.Ghci.LoadedModule: [relPath] :: LoadedModule -> FilePath
+ Tricorder.Daemon.Ghci.LoadedModule: [relPath] :: LoadedModule -> Relative
- Tricorder.Daemon.Ghci.Loading: Loading :: Int -> Int -> Text -> FilePath -> Loading
+ Tricorder.Daemon.Ghci.Loading: Loading :: Int -> Int -> Text -> Any -> Loading
- Tricorder.Daemon.Ghci.Loading: [sourceFile] :: Loading -> FilePath
+ Tricorder.Daemon.Ghci.Loading: [sourceFile] :: Loading -> Any
- Tricorder.Daemon.Ghci.Message: Message :: Severity -> FilePath -> Position -> Position -> [Text] -> Message
+ Tricorder.Daemon.Ghci.Message: Message :: Severity -> DiagnosticLocation -> Position -> Position -> [Text] -> Message
- Tricorder.Daemon.Ghci.Message: [file] :: Message -> FilePath
+ Tricorder.Daemon.Ghci.Message: [file] :: Message -> DiagnosticLocation
- Tricorder.Daemon.Ghci.Output: parseShowModules :: [Text] -> [(Text, FilePath)]
+ Tricorder.Daemon.Ghci.Output: parseShowModules :: [Text] -> [(Text, Any)]
- Tricorder.Daemon.Ghci.Path: pathSuffixesAsModuleName :: FilePath -> [Text]
+ Tricorder.Daemon.Ghci.Path: pathSuffixesAsModuleName :: Path path => path -> [Text]
- Tricorder.Daemon.Ghci.Process: add :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, File :> es, Log :> es) => Process -> FilePath -> FilePath -> (Loading -> Eff es ()) -> Eff es LoadResult
+ Tricorder.Daemon.Ghci.Process: add :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, Handles :> es, Log :> es) => Process -> Any -> Absolute -> (Loading -> Eff es ()) -> Eff es LoadResult
- Tricorder.Daemon.Ghci.Process: collectResult :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, File :> es, Log :> es) => Process -> [Text] -> FilePath -> Eff es LoadResult
+ Tricorder.Daemon.Ghci.Process: collectResult :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, Handles :> es, Log :> es) => Process -> [Text] -> Absolute -> Eff es LoadResult
- Tricorder.Daemon.Ghci.Process: drainUntil :: forall (es :: [Effect]). (File :> es, Log :> es) => Handle -> Text -> (Text -> Eff es ()) -> Eff es [Text]
+ Tricorder.Daemon.Ghci.Process: drainUntil :: forall (es :: [Effect]). (Handles :> es, Log :> es) => Handle -> Text -> (Text -> Eff es ()) -> Eff es [Text]
- Tricorder.Daemon.Ghci.Process: exec :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, File :> es, Log :> es) => Process -> Text -> (Loading -> Eff es ()) -> Eff es [Text]
+ Tricorder.Daemon.Ghci.Process: exec :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, Handles :> es, Log :> es) => Process -> Text -> (Loading -> Eff es ()) -> Eff es [Text]
- Tricorder.Daemon.Ghci.Process: interruptGhci :: forall (es :: [Effect]). (Process :> es, Concurrent :> es, File :> es) => Process -> Eff es ()
+ Tricorder.Daemon.Ghci.Process: interruptGhci :: forall (es :: [Effect]). (Process :> es, Concurrent :> es, Handles :> es) => Process -> Eff es ()
- Tricorder.Daemon.Ghci.Process: reload :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, File :> es, Log :> es) => Process -> FilePath -> (Loading -> Eff es ()) -> Eff es LoadResult
+ Tricorder.Daemon.Ghci.Process: reload :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, Handles :> es, Log :> es) => Process -> Absolute -> (Loading -> Eff es ()) -> Eff es LoadResult
- Tricorder.Daemon.Ghci.Process: unadd :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, File :> es, Log :> es) => Process -> Text -> FilePath -> (Loading -> Eff es ()) -> Eff es LoadResult
+ Tricorder.Daemon.Ghci.Process: unadd :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, Handles :> es, Log :> es) => Process -> Text -> Absolute -> (Loading -> Eff es ()) -> Eff es LoadResult
- Tricorder.Daemon.Ghci.Process: waitForBannerOrFail :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, File :> es, Timeout :> es) => Second -> Handle -> Handle -> Eff es ()
+ Tricorder.Daemon.Ghci.Process: waitForBannerOrFail :: forall (es :: [Effect]). (Conc :> es, Concurrent :> es, Handles :> es, Timeout :> es) => Second -> Handle -> Handle -> Eff es ()
- Tricorder.Daemon.Ghci.Process: with :: forall (es :: [Effect]) (stage :: Stage) a. (Process :> es, Conc :> es, Concurrent :> es, File :> es, Log :> es, Timeout :> es) => Config -> RenderedCommand stage -> FilePath -> (Loading -> Eff es ()) -> (Process -> Eff es ()) -> (Process -> [Text] -> Eff es a) -> Eff es a
+ Tricorder.Daemon.Ghci.Process: with :: forall (es :: [Effect]) (stage :: Stage) a. (Process :> es, Conc :> es, Concurrent :> es, Handles :> es, Log :> es, Timeout :> es) => Config -> RenderedCommand stage -> Absolute -> (Loading -> Eff es ()) -> (Process -> Eff es ()) -> (Process -> [Text] -> Eff es a) -> Eff es a
- Tricorder.Daemon.Ghci.Result: collectResult :: FilePath -> [Text] -> [(Text, FilePath)] -> [Text] -> LoadResult
+ Tricorder.Daemon.Ghci.Result: collectResult :: Absolute -> [Text] -> [(Text, Any)] -> [Text] -> LoadResult
- Tricorder.Daemon.Ghci.Result: collectResultCustom :: FilePath -> [Load] -> [(Text, FilePath)] -> [Text] -> LoadResult
+ Tricorder.Daemon.Ghci.Result: collectResultCustom :: Absolute -> [Load] -> [(Text, Any)] -> [Text] -> LoadResult
- Tricorder.Daemon.Ghci.Session: run :: forall (es :: [Effect]) a. (Conc :> es, Concurrent :> es, File :> es, Log :> es, Process :> es, Timeout :> es) => Eff (Session ': es) a -> Eff es a
+ Tricorder.Daemon.Ghci.Session: run :: forall (es :: [Effect]) a. (Conc :> es, Concurrent :> es, Handles :> es, Log :> es, Process :> es, Timeout :> es) => Eff (Session ': es) a -> Eff es a
- Tricorder.Daemon.Ghci.Session: with :: forall a (es :: [Effect]). (HasCallStack, Session :> es) => (BuildProgress -> Eff es ()) -> RenderedCommand 'Build -> ProjectRoot -> (LoadResult -> Controls (Eff es) -> Eff es a) -> Eff es a
+ Tricorder.Daemon.Ghci.Session: with :: forall a (es :: [Effect]). (HasCallStack, Session :> es) => (Progress -> Eff es ()) -> RenderedCommand 'Build -> ProjectRoot -> (LoadResult -> Controls (Eff es) -> Eff es a) -> Eff es a
- Tricorder.Daemon.HookDispatch: main :: forall (es :: [Effect]). (Process :> es, Reader ProjectRoot :> es, Sub WatchedFile :> es) => Session -> Eff es Void
+ Tricorder.Daemon.HookDispatch: main :: forall (es :: [Effect]). (Log :> es, Process :> es, Reader ProjectRoot :> es, Sub WatchedFile :> es) => Session -> Eff es Void
- Tricorder.Daemon.Hpack.Effect: [Hpack] :: forall (a :: Type -> Type). FilePath -> Hpack a (Either Text Result)
+ Tricorder.Daemon.Hpack.Effect: [Hpack] :: forall (a :: Type -> Type). Absolute -> Hpack a (Either Text Result)
- Tricorder.Daemon.Hpack.Effect: hpack :: forall (es :: [Effect]). (HasCallStack, Hpack :> es) => FilePath -> Eff es (Either Text Result)
+ Tricorder.Daemon.Hpack.Effect: hpack :: forall (es :: [Effect]). (HasCallStack, Hpack :> es) => Absolute -> Eff es (Either Text Result)
- Tricorder.Daemon.TestRunner: run :: forall (es :: [Effect]) a. (Conc :> es, Concurrent :> es, File :> es, Log :> es, Process :> es, Reader ProjectRoot :> es, Timeout :> es) => Eff (TestRunner ': es) a -> Eff es a
+ Tricorder.Daemon.TestRunner: run :: forall (es :: [Effect]) a. (Conc :> es, Concurrent :> es, Handles :> es, Log :> es, Process :> es, Reader ProjectRoot :> es, Timeout :> es) => Eff (TestRunner ': es) a -> Eff es a
- Tricorder.Daemon.Watch: WatchedFile :: FilePath -> Event -> WatchedFile
+ Tricorder.Daemon.Watch: WatchedFile :: Any -> Event -> WatchedFile
- Tricorder.Daemon.Watch: [path] :: WatchedFile -> FilePath
+ Tricorder.Daemon.Watch: [path] :: WatchedFile -> Any
- Tricorder.Daemon.Watch: files :: forall (es :: [Effect]). (Debounce FilePath :> es, FileWatcher :> es, Pub WatchedFile :> es) => ProjectRoot -> Session -> Eff es Void
+ Tricorder.Daemon.Watch: files :: forall (es :: [Effect]). (Debounce FilePath :> es, FileWatcher :> es, Log :> es, Pub WatchedFile :> es) => ProjectRoot -> Session -> Eff es Void
- Tricorder.Daemon.Watch: publishChange :: forall (es :: [Effect]). (Pub CabalChangeDetected :> es, Pub SourceChangeDetected :> es) => WatchedFile -> Eff es ()
+ Tricorder.Daemon.Watch: publishChange :: forall (es :: [Effect]). (Pub ProjectChangeDetected :> es, Pub SourceChangeDetected :> es) => WatchedFile -> Eff es ()
- Tricorder.Session.CabalFile: CabalFile :: FilePath -> GenericPackageDescription -> CabalFile
+ Tricorder.Session.CabalFile: CabalFile :: Absolute -> GenericPackageDescription -> CabalFile
- Tricorder.Session.CabalFile: [projectFilePath] :: CabalFile -> FilePath
+ Tricorder.Session.CabalFile: [projectFilePath] :: CabalFile -> Absolute
- Tricorder.Session.CabalFile: discoverCabalPackages :: forall (es :: [Effect]). (Env :> es, FileSystem :> es, Glob :> es, Reader ProjectRoot :> es) => Eff es (Either Text [FilePath])
+ Tricorder.Session.CabalFile: discoverCabalPackages :: forall (es :: [Effect]). (FileSystem :> es, Glob :> es, Reader ProjectRoot :> es) => Eff es (Either Text [Absolute])
- Tricorder.Session.CabalFile: discoverPackages :: forall (es :: [Effect]). (Env :> es, FileSystem :> es, Glob :> es, Input StackProject :> es, Reader ProjectRoot :> es) => Eff es (Either Text [FilePath])
+ Tricorder.Session.CabalFile: discoverPackages :: forall (es :: [Effect]). (FileSystem :> es, Glob :> es, Input StackProject :> es, Reader ProjectRoot :> es) => Eff es (Either Text [Absolute])
- Tricorder.Session.CabalFile: discoverStackPackages :: forall (es :: [Effect]). (Input StackProject :> es, Reader ProjectRoot :> es) => Eff es (Either Text [FilePath])
+ Tricorder.Session.CabalFile: discoverStackPackages :: forall (es :: [Effect]). (Input StackProject :> es, Reader ProjectRoot :> es) => Eff es (Either Text [Absolute])
- Tricorder.Session.CabalFile: inputCabalFiles :: forall (es :: [Effect]) a. (Env :> es, FileSystem :> es, Glob :> es, Input StackProject :> es, Log :> es, Reader ProjectRoot :> es) => Eff (Input [CabalFile] ': es) a -> Eff es a
+ Tricorder.Session.CabalFile: inputCabalFiles :: forall (es :: [Effect]) a. (FileSystem :> es, Glob :> es, Input StackProject :> es, Log :> es, Reader ProjectRoot :> es) => Eff (Input [CabalFile] ': es) a -> Eff es a
- Tricorder.Session.CabalFile: readProjectFile :: forall (es :: [Effect]). FileSystem :> es => FilePath -> Eff es (Either FilePath CabalFile)
+ Tricorder.Session.CabalFile: readProjectFile :: forall (es :: [Effect]). FileSystem :> es => Absolute -> Eff es (Either Absolute CabalFile)
- Tricorder.Session.Hook: run :: forall (es :: [Effect]). (Process :> es, Reader ProjectRoot :> es) => Hook -> Eff es ()
+ Tricorder.Session.Hook: run :: forall (es :: [Effect]). (Log :> es, Process :> es, Reader ProjectRoot :> es) => Hook -> Eff es ()
- Tricorder.Session.StackProject: StackProject :: [FilePath] -> StackProject
+ Tricorder.Session.StackProject: StackProject :: [Relative] -> StackProject
- Tricorder.Session.StackProject: [packages] :: StackProject -> [FilePath]
+ Tricorder.Session.StackProject: [packages] :: StackProject -> [Relative]
- Tricorder.Session.Stage.Test.Session: ResolvedTestOptions :: OutputMode -> Millisecond -> Maybe ByteSize -> ResolvedTestOptions
+ Tricorder.Session.Stage.Test.Session: ResolvedTestOptions :: OutputMode -> AsRawUnit Millisecond -> Maybe ByteSize -> ResolvedTestOptions
- Tricorder.Session.Stage.Test.Session: [timeout] :: ResolvedTestOptions -> Millisecond
+ Tricorder.Session.Stage.Test.Session: [timeout] :: ResolvedTestOptions -> AsRawUnit Millisecond
- Tricorder.Session.WatchDirs: WatchDirs :: [FilePath] -> WatchDirs
+ Tricorder.Session.WatchDirs: WatchDirs :: [Absolute] -> WatchDirs
- Tricorder.Session.WatchDirs: [getWatchDirs] :: WatchDirs -> [FilePath]
+ Tricorder.Session.WatchDirs: [getWatchDirs] :: WatchDirs -> [Absolute]
- Tricorder.Session.WatchDirs: allSourceDirs :: GenericPackageDescription -> [FilePath]
+ Tricorder.Session.WatchDirs: allSourceDirs :: GenericPackageDescription -> Either Text [Any]
- Tricorder.Session.WatchDirs: resolve :: ProjectRoot -> [CabalFile] -> Config -> [Target] -> WatchDirs
+ Tricorder.Session.WatchDirs: resolve :: ProjectRoot -> [CabalFile] -> Config -> [Target] -> Either Text WatchDirs
- Tricorder.Session.WatchDirs: sourceDirsForTarget :: GenericPackageDescription -> Target -> [FilePath]
+ Tricorder.Session.WatchDirs: sourceDirsForTarget :: GenericPackageDescription -> Target -> Either Text [Any]
- Tricorder.Socket.Client: isDaemonReady :: forall (es :: [Effect]). UnixSocket :> es => FilePath -> Eff es Bool
+ Tricorder.Socket.Client: isDaemonReady :: forall path (es :: [Effect]). (Path path, UnixSocket :> es) => path -> Eff es Bool
- Tricorder.Socket.Client: queryDiagnostic :: forall (es :: [Effect]). (File :> es, UnixSocket :> es) => FilePath -> Int -> Eff es (Either Text Diagnostic)
+ Tricorder.Socket.Client: queryDiagnostic :: forall (es :: [Effect]) path. (Handles :> es, Path path, UnixSocket :> es) => path -> Int -> Eff es (Either Text Diagnostic)
- Tricorder.Socket.Client: queryStatus :: forall (es :: [Effect]). (File :> es, UnixSocket :> es) => FilePath -> Eff es (Either Text BuildState)
+ Tricorder.Socket.Client: queryStatus :: forall (es :: [Effect]) path. (Handles :> es, Path path, UnixSocket :> es) => path -> Eff es (Either Text State)
- Tricorder.Socket.Client: queryStatusWait :: forall (es :: [Effect]). (File :> es, UnixSocket :> es) => FilePath -> Eff es (Either Text BuildState)
+ Tricorder.Socket.Client: queryStatusWait :: forall (es :: [Effect]) path. (Handles :> es, Path path, UnixSocket :> es) => path -> Eff es (Either Text State)
- Tricorder.Socket.Client: queryWatch :: forall (es :: [Effect]). (Delay :> es, File :> es, UnixSocket :> es) => FilePath -> Eff es Bool -> (Either Restarting BuildState -> Eff es ()) -> Eff es ()
+ Tricorder.Socket.Client: queryWatch :: forall path (es :: [Effect]). (Delay :> es, Handles :> es, Path path, UnixSocket :> es) => path -> Eff es Bool -> (Either Restarting State -> Eff es ()) -> Eff es ()
- Tricorder.Socket.Client: requestShutdown :: forall (es :: [Effect]). (File :> es, UnixSocket :> es) => IfThereArePendingQueries -> FilePath -> Eff es (Either Text ())
+ Tricorder.Socket.Client: requestShutdown :: forall (es :: [Effect]) path. (Handles :> es, Path path, UnixSocket :> es) => IfThereArePendingQueries -> path -> Eff es (Either Text ())
- Tricorder.Socket.Server: main :: forall (es :: [Effect]). (Conc :> es, Exit :> es, File :> es, FileSystem :> es, IdleTimer :> es, Input BuildId :> es, Log :> es, Reader SocketPath :> es, Sub BuildPhase :> es, UnixSocket :> es, Waiters :> es) => Eff es Void
+ Tricorder.Socket.Server: main :: forall (es :: [Effect]). (Conc :> es, Exit :> es, FileSystem :> es, Handles :> es, IdleTimer :> es, Input Id :> es, Log :> es, Reader SocketPath :> es, Sub Phase :> es, UnixSocket :> es, Waiters :> es) => Eff es Void
- Tricorder.Socket.UnixSocket: bind :: forall (es :: [Effect]). (HasCallStack, UnixSocket :> es) => FilePath -> Eff es Socket
+ Tricorder.Socket.UnixSocket: bind :: forall path (es :: [Effect]). (HasCallStack, UnixSocket :> es, Path path) => path -> Eff es Socket
- Tricorder.Socket.UnixSocket: runIO :: forall (es :: [Effect]) a. (File :> es, IOE :> es) => Eff (UnixSocket ': es) a -> Eff es a
+ Tricorder.Socket.UnixSocket: runIO :: forall (es :: [Effect]) a. (Handles :> es, IOE :> es) => Eff (UnixSocket ': es) a -> Eff es a
- Tricorder.Socket.UnixSocket: runScripted :: forall (es :: [Effect]) a. (File :> es, IOE :> es) => [SocketScript] -> Eff (UnixSocket ': es) a -> Eff es a
+ Tricorder.Socket.UnixSocket: runScripted :: forall (es :: [Effect]) a. (Handles :> es, IOE :> es) => [SocketScript] -> Eff (UnixSocket ': es) a -> Eff es a
- Tricorder.Socket.UnixSocket: withConnection :: forall a (es :: [Effect]). (HasCallStack, UnixSocket :> es) => FilePath -> (Handle -> Eff es a) -> Eff es a
+ Tricorder.Socket.UnixSocket: withConnection :: forall path a (es :: [Effect]). (HasCallStack, UnixSocket :> es, Path path) => path -> (Handle -> Eff es a) -> Eff es a
- Tricorder.SourceLookup: ProjectSourceDirs :: [FilePath] -> ProjectSourceDirs
+ Tricorder.SourceLookup: ProjectSourceDirs :: [Absolute] -> ProjectSourceDirs
- Tricorder.SourceLookup.PackageStore: [Add] :: forall (a :: Type -> Type). PackageId -> ByteString -> PackageStore a [Char]
+ Tricorder.SourceLookup.PackageStore: [Add] :: forall (a :: Type -> Type). PackageId -> ByteString -> PackageStore a (Either Text Absolute)
- Tricorder.SourceLookup.PackageStore: [GetPath] :: forall (a :: Type -> Type). PackageId -> PackageStore a (Maybe FilePath)
+ Tricorder.SourceLookup.PackageStore: [GetPath] :: forall (a :: Type -> Type). PackageId -> PackageStore a (Maybe Absolute)
- Tricorder.SourceLookup.PackageStore: add :: forall (es :: [Effect]). (HasCallStack, PackageStore :> es) => PackageId -> ByteString -> Eff es FilePath
+ Tricorder.SourceLookup.PackageStore: add :: forall (es :: [Effect]). (HasCallStack, PackageStore :> es) => PackageId -> ByteString -> Eff es (Either Text Absolute)
- Tricorder.SourceLookup.PackageStore: getPath :: forall (es :: [Effect]). (HasCallStack, PackageStore :> es) => PackageId -> Eff es (Maybe FilePath)
+ Tricorder.SourceLookup.PackageStore: getPath :: forall (es :: [Effect]). (HasCallStack, PackageStore :> es) => PackageId -> Eff es (Maybe Absolute)
- Tricorder.SourceLookup.Tarball: TarballAt :: FilePath -> TarballOutcome
+ Tricorder.SourceLookup.Tarball: TarballAt :: Absolute -> TarballOutcome
- Tricorder.SourceLookup.Tarball: readModuleMember :: forall (es :: [Effect]). FileSystem :> es => FilePath -> ModuleName -> Eff es (Maybe Text)
+ Tricorder.SourceLookup.Tarball: readModuleMember :: forall (es :: [Effect]). FileSystem :> es => Absolute -> ModuleName -> Eff es (Maybe Text)

Files

CHANGELOG.md view
@@ -7,6 +7,68 @@  ## [Unreleased] +## [1.1.0.0] - 2026-11-18++### Changed++- Tricorder will now look upwards in the directory tree for recognized Cabal or+  Stack files to find the root of the project to build. So if you run+  `tricorder ui` from a subdirectory in your repo, Tricorder will walk upwards+  to the root of your repo (or to the root of the package you're in, if you are+  in one package of a multi-package repo), and use that as the root of the+  project. Defaults to the current working directory (the old behavior) if no+  Cabal or Stack files are found.+- When the project root is a package inside a larger project, Tricorder now+  also looks in ancestor directories for `stack.yaml` (to decide whether to use+  Stack, and to reload when it changes) and `cabal.project` (to decide whether+  to use multi-repl), as `stack` and `cabal` do. Tricorder still only works on+  the package it was started in.+- Changes to `cabal.project.local` and `cabal.project.freeze` now trigger a+  reload, and `~/.config/cabal/config` is now consulted in addition to+  `~/.cabal/config`.+- Failed hooks now output a message to the log file.+- `tricorder daemon info` now outputs the full session instead of just the+  build targets and watch directories.+- Moved Tricorder's default log file location from `XDG_RUNTIME_DIR` to+  `XDG_CACHE_HOME`. This is more sensible for users, since `XDG_RUNTIME_DIR`+  can sometimes be mounted as a `tmpfs` system, meaning Tricorder is filling up+  developers' RAM unnecessarily.+- Tricorder will now truncate the log file on daemon startup, if it exists. To+  prevent this from happening, set the environment variable+  `TRICORDER_NO_LOG_TRUNCATE=1`.+- Atomic writes, which is the default for many editors like Neovim and Emacs,+  no longer trigger the `haskell.file_added` hook instead of the+  `haskell.file_modified` hook. This was caused by how atomic writes work: when+  a file is modified in Neovim or Emacs or any editor using atomic writing,+  they first save the file with the changed content in a separate location,+  remove the existing, old version of the file, and move the file with the+  changes from the temporary location into the location of the old one. To+  Tricorder, this looked like you first removed the existing file, and then+  re-added it, which was debounced and merged into a single "added" event. Now+  a "remove" immediately followed by an "added" is considered a "modified"+  event. Granted, there are some edge-cases here where there might be+  legitimate "remove, added" events in the same debounce window for a single+  file that should be treated as separate calls to `haskell.file_removed` and+  `haskell.file_added` hooks, but we'll leave this for later.+- Object keys from `tricorder status --json` are now formatted in `quiet_snake`+  casing.++### Fixed++- A `stack.yaml` without a `packages` key no longer fails to parse. Like Stack,+  Tricorder now defaults `packages` to `["."]`.+- `Shift + R` in `tricorder ui` raised an error about+  `Invalid argument 'restart'`. It used the now-removed `tricorder restart`+  command to restart the daemon, but has now been fixed.+- Errors would sometimes linger on even though the source of the error was+  fixed or changed. This was especially prevalent when moving existing data+  types imported from other modules into a new module. Even though you would+  fix the references to that data type in the importing modules, Tricorder+  would complain that they attempt to import the data type from the old module.+  This has now been fixed.+- Fixed Haskell file hooks not triggering.+- Fixed reported compilation errors hanging around after you've fixed them.+ ## [1.0.0.0] - 2026-10-29  ### Added@@ -17,6 +79,8 @@ - Flag `--prevent-daemon` to prevent Tricorder from starting the daemon if it   is not already running. This is the inverse of the previous `--start-daemon`   flag.+- Flag `--help-json` for `tricorder test suites`, which prints the JSON Schema+  (draft 2020-12) of the output of `tricorder test suites --json`.  ### Changed 
+ help/Main.hs view
@@ -0,0 +1,7 @@+import System.IO qualified as IO++import Tricorder.CLI.Docs (renderReference)+++main :: IO ()+main = IO.putStrLn $ toString renderReference
− src/Tricorder/Build.hs
@@ -1,100 +0,0 @@-module Tricorder.Build-    ( BuildState (..)-    , BuildId (..)-    , BuildPhase (..)-    , BuildProgress (..)-    , BuildResult (..)-    , PostBuild (..)-    , Diagnostic (..)-    , Severity (..)-    )-where--import Atelier.Effects.Clock (UTCTime)-import Data.Aeson (FromJSON (..), ToJSON (..), withText)-import GHC.Generics (Generically (..))--import Tricorder.Build.Duration (Duration)-import Tricorder.Session.TestTarget (TestTarget)--import Tricorder.Build.EvalComment qualified as Eval-import Tricorder.Build.Test qualified as Test---data BuildState = BuildState-    { phase :: BuildPhase-    , buildId :: BuildId-    }-    deriving stock (Eq, Generic, Show)-    deriving (FromJSON, ToJSON) via Generically BuildState---newtype BuildId = BuildId {getBuildId :: Int}-    deriving stock (Eq, Show)-    deriving (FromJSON, Num, ToJSON) via Int---data BuildPhase-    = Starting-    | Building [TestTarget] BuildProgress-    | Failed Text-    | PostBuilding BuildResult PostBuild-    | Finished BuildResult PostBuild-    deriving stock (Eq, Generic, Show)-    deriving (FromJSON, ToJSON) via Generically BuildPhase---data BuildProgress = BuildProgress-    { compiled :: Int-    , total :: Int-    }-    deriving stock (Eq, Generic, Show)-    deriving (FromJSON, ToJSON) via Generically BuildProgress---data BuildResult = BuildResult-    { completedAt :: UTCTime-    , duration :: Duration-    , moduleCount :: Int-    , diagnostics :: [Diagnostic]-    }-    deriving stock (Eq, Generic, Show)-    deriving (FromJSON, ToJSON) via Generically BuildResult---data PostBuild = PostBuild-    { testSuites :: Test.Suites-    , evalComments :: Eval.Phase-    }-    deriving stock (Eq, Generic, Show)-    deriving (FromJSON, ToJSON) via Generically PostBuild---data Diagnostic = Diagnostic-    { severity :: Severity-    , file :: FilePath-    , line :: Int-    , col :: Int-    , endLine :: Int-    , endCol :: Int-    , title :: Text-    , text :: Text-    }-    deriving stock (Eq, Generic, Show)-    deriving (FromJSON, ToJSON) via Generically Diagnostic---data Severity = SError | SWarning-    deriving stock (Eq, Ord, Show)---instance FromJSON Severity where-    parseJSON = withText "Severity" \case-        "error" -> pure SError-        "warning" -> pure SWarning-        other -> fail $ "unknown severity: " <> toString other---instance ToJSON Severity where-    toJSON SError = "error"-    toJSON SWarning = "warning"
src/Tricorder/Build/ByteSize.hs view
@@ -7,6 +7,9 @@     ) where +import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (ToJSON)+import GHC.Generics (Generically (..)) import Text.Megaparsec (Parsec, eof, parseMaybe) import Text.Megaparsec.Char (space, string') import Text.Megaparsec.Char.Lexer (decimal)@@ -17,6 +20,7 @@  data ByteSize = ByteSize {amount :: Integer, unit :: Unit}     deriving stock (Eq, Generic, Ord)+    deriving (ToJSON) via QuietSnake ByteSize   instance Show ByteSize where@@ -36,6 +40,7 @@     | PB     | PiB     deriving stock (Eq, Generic, Ord, Show)+    deriving (ToJSON) via Generically Unit   asBytes :: ByteSize -> Integer
src/Tricorder/Build/Changes.hs view
@@ -1,22 +1,23 @@ module Tricorder.Build.Changes     ( ChangeKind (..)-    , CabalChangeDetected (..)+    , ProjectChangeDetected (..)     , SourceChangeDetected (..)     ) where  import Atelier.Effects.FileWatcher.Event qualified as FileWatcher (Event)+import Atelier.FileSystem.Path qualified as Path   -- | Classifies what kind of file change triggered a dirty signal.--- 'CabalChange' takes priority over 'SourceChange': if both fire before the+-- 'ProjectChange' takes priority over 'SourceChange': if both fire before the -- next build starts, the session will be fully restarted rather than reloaded.-data ChangeKind = SourceChange | CabalChange deriving stock (Eq, Ord, Show)+data ChangeKind = SourceChange | ProjectChange deriving stock (Eq, Ord, Show)  -data CabalChangeDetected = CabalChangeDetected FilePath FileWatcher.Event+data ProjectChangeDetected = ProjectChangeDetected Path.Any FileWatcher.Event     deriving stock (Eq, Show)  -data SourceChangeDetected = SourceChangeDetected FilePath FileWatcher.Event+data SourceChangeDetected = SourceChangeDetected Path.Any FileWatcher.Event     deriving stock (Eq, Show)
+ src/Tricorder/Build/Diagnostic.hs view
@@ -0,0 +1,21 @@+module Tricorder.Build.Diagnostic (Diagnostic (..)) where++import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (FromJSON, ToJSON)++import Tricorder.Build.DiagnosticLocation (DiagnosticLocation)+import Tricorder.Build.Severity (Severity)+++data Diagnostic = Diagnostic+    { severity :: Severity+    , file :: DiagnosticLocation+    , line :: Int+    , col :: Int+    , endLine :: Int+    , endCol :: Int+    , title :: Text+    , text :: Text+    }+    deriving stock (Eq, Generic, Show)+    deriving (FromJSON, ToJSON) via QuietSnake Diagnostic
+ src/Tricorder/Build/DiagnosticLocation.hs view
@@ -0,0 +1,25 @@+module Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..), map) where++import Data.Aeson (FromJSON, ToJSON)+import GHC.Generics (Generically (..))+import Prelude hiding (map)++import Atelier.FileSystem.Path qualified as Path+++data DiagnosticLocation+    = Locationless+    | Location Path.Any+    deriving stock (Eq, Generic, Ord, Show)+    deriving (FromJSON, ToJSON) via Generically DiagnosticLocation+++instance ToText DiagnosticLocation where+    toText = \case+        Locationless -> "<no location info>"+        Location path -> toText path+++map :: (Path.Any -> Path.Any) -> DiagnosticLocation -> DiagnosticLocation+map _ Locationless = Locationless+map f (Location path) = Location $ f path
src/Tricorder/Build/EvalComment.hs view
@@ -32,6 +32,7 @@     ) import Text.Megaparsec.Char (char, hspace, space, string) +import Atelier.FileSystem.Path qualified as Path import Data.Aeson.KeyMap qualified as KM import Data.Text qualified as T @@ -51,7 +52,7 @@     Found comments -> anyRunningComments comments  -data Comments = Comments {getComments :: NonEmpty Evaluation}+newtype Comments = Comments {getComments :: NonEmpty Evaluation}     deriving stock (Eq, Generic, Show)     deriving (FromJSON, ToJSON) via Generically Comments @@ -61,7 +62,7 @@   data Evaluation = Evaluation-    { file :: FilePath+    { file :: Path.Relative     , comment :: Comment     , state :: State     }
+ src/Tricorder/Build/Id.hs view
@@ -0,0 +1,8 @@+module Tricorder.Build.Id (Id (..)) where++import Data.Aeson (FromJSON, ToJSON)+++newtype Id = Id {getId :: Int}+    deriving stock (Eq, Show)+    deriving (FromJSON, Num, ToJSON) via Int
+ src/Tricorder/Build/Phase.hs view
@@ -0,0 +1,19 @@+module Tricorder.Build.Phase (Phase (..)) where++import Data.Aeson (FromJSON, ToJSON)+import GHC.Generics (Generically (..))++import Tricorder.Build.PostBuild (PostBuild)+import Tricorder.Build.Progress (Progress)+import Tricorder.Build.Result (Result)+import Tricorder.Session.TestTarget (TestTarget)+++data Phase+    = Starting+    | Building [TestTarget] Progress+    | Failed Text+    | PostBuilding Result PostBuild+    | Finished Result PostBuild+    deriving stock (Eq, Generic, Show)+    deriving (FromJSON, ToJSON) via Generically Phase
+ src/Tricorder/Build/PostBuild.hs view
@@ -0,0 +1,15 @@+module Tricorder.Build.PostBuild (PostBuild (..)) where++import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (FromJSON, ToJSON)++import Tricorder.Build.EvalComment qualified as Eval+import Tricorder.Build.Test qualified as Test+++data PostBuild = PostBuild+    { testSuites :: Test.Suites+    , evalComments :: Eval.Phase+    }+    deriving stock (Eq, Generic, Show)+    deriving (FromJSON, ToJSON) via QuietSnake PostBuild
+ src/Tricorder/Build/Progress.hs view
@@ -0,0 +1,12 @@+module Tricorder.Build.Progress (Progress (..)) where++import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (FromJSON, ToJSON)+++data Progress = Progress+    { compiled :: Int+    , total :: Int+    }+    deriving stock (Eq, Generic, Show)+    deriving (FromJSON, ToJSON) via QuietSnake Progress
+ src/Tricorder/Build/Result.hs view
@@ -0,0 +1,18 @@+module Tricorder.Build.Result (Result (..)) where++import Atelier.Effects.Clock (UTCTime)+import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (FromJSON, ToJSON)++import Tricorder.Build.Diagnostic (Diagnostic)+import Tricorder.Build.Duration (Duration)+++data Result = Result+    { completedAt :: UTCTime+    , duration :: Duration+    , moduleCount :: Int+    , diagnostics :: [Diagnostic]+    }+    deriving stock (Eq, Generic, Show)+    deriving (FromJSON, ToJSON) via QuietSnake Result
+ src/Tricorder/Build/Severity.hs view
@@ -0,0 +1,19 @@+module Tricorder.Build.Severity (Severity (..)) where++import Data.Aeson (FromJSON (..), ToJSON (..), withText)+++data Severity = Error | Warning+    deriving stock (Eq, Ord, Show)+++instance FromJSON Severity where+    parseJSON = withText "Severity" \case+        "error" -> pure Error+        "warning" -> pure Warning+        other -> fail $ "unknown severity: " <> toString other+++instance ToJSON Severity where+    toJSON Error = "error"+    toJSON Warning = "warning"
+ src/Tricorder/Build/State.hs view
@@ -0,0 +1,15 @@+module Tricorder.Build.State (State (..)) where++import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (FromJSON, ToJSON)++import Tricorder.Build.Id (Id)+import Tricorder.Build.Phase (Phase)+++data State = State+    { phase :: Phase+    , buildId :: Id+    }+    deriving stock (Eq, Generic, Show)+    deriving (FromJSON, ToJSON) via QuietSnake State
src/Tricorder/CLI/App.hs view
@@ -5,8 +5,7 @@ import Atelier.Effects.Console (Console) import Atelier.Effects.Delay (Delay) import Atelier.Effects.Exit (Exit)-import Atelier.Effects.File (File)-import Atelier.Effects.FileSystem (FileSystem)+import Atelier.Effects.Handles (Handles) import Atelier.Effects.Input (Input) import Atelier.Effects.Log (Log) import Atelier.Effects.Posix.Daemons (Daemons)@@ -14,8 +13,9 @@ import Atelier.Effects.Timeout (Timeout) import Effectful (IOE) import Effectful.Concurrent (Concurrent)+import Effectful.FileSystem (FileSystem) import Effectful.Provider (Provider_)-import Effectful.Reader.Static (Reader, ask, asks)+import Effectful.Reader.Static (Reader) import Tricorder.API.Command     ( Command (..)     , EvalCommentsOptions (..)@@ -25,6 +25,7 @@ import Prelude hiding (force)  import Atelier.Effects.Console qualified as Console+import Effectful.Reader.Static qualified as Reader import Tricorder.API.IfDaemonIsStopped qualified as IfDaemonIsStopped  import Tricorder.CLI.Daemon (startDaemon, waitForDaemon)@@ -33,7 +34,6 @@ import Tricorder.CLI.UI.Brick (Brick) import Tricorder.CLI.UI.BrickChan (BrickChan) import Tricorder.Daemon.DaemonInfo (DaemonInfo)-import Tricorder.Runtime (LogPath (..), PidFile (..), SocketPath (..)) import Tricorder.Session.CabalFile (CabalFile) import Tricorder.Socket.Client (isDaemonRunning) import Tricorder.Socket.UnixSocket (UnixSocket)@@ -44,6 +44,9 @@ import Tricorder.CLI.App.Daemon qualified as Daemon import Tricorder.CLI.App.Test qualified as Test import Tricorder.CLI.UI.Keys qualified as Keys+import Tricorder.Runtime.LogPath qualified as Runtime (LogPath (..))+import Tricorder.Runtime.PidFile qualified as Runtime (PidFile)+import Tricorder.Runtime.SocketPath qualified as Runtime (SocketPath) import Tricorder.Session.Stage.Build.Session qualified as Build (Session)  @@ -57,10 +60,10 @@        , Daemons :> es        , Delay :> es        , Exit :> es-       , File :> es        , FileSystem :> es        , GhcPkg :> es        , Hackage :> es+       , Handles :> es        , IOE :> es        , Input Build.Session :> es        , Input DaemonInfo :> es@@ -71,15 +74,15 @@        , Provider_ Console Console.Output :> es        , Reader Command :> es        , Reader Keys.Config :> es-       , Reader LogPath :> es-       , Reader PidFile :> es-       , Reader SocketPath :> es+       , Reader Runtime.LogPath :> es+       , Reader Runtime.PidFile :> es+       , Reader Runtime.SocketPath :> es        , Timeout :> es        , UnixSocket :> es        )     => Eff es () run =-    ask >>= \case+    Reader.ask >>= \case         Status opts -> do             running <- isDaemonRunning             if@@ -90,7 +93,7 @@                 | not running -> Console.putStrLn "Stopped."                 | otherwise -> showStatus opts         Log logMode -> do-            logFile <- asks @LogPath (.getLogPath)+            Runtime.LogPath logFile <- Reader.ask             case logMode of                 ShowLog -> showLog logFile                 ShowLogPath -> Console.putTextLn (toText logFile)
src/Tricorder/CLI/App/Daemon.hs view
@@ -2,7 +2,7 @@  import Atelier.Effects.Console (Console) import Atelier.Effects.Delay (Delay)-import Atelier.Effects.File (File)+import Atelier.Effects.Handles (Handles) import Atelier.Effects.Input (Input, input) import Atelier.Effects.Posix.Daemons (Daemons) import Atelier.Effects.Timeout (Timeout)@@ -17,7 +17,8 @@ import Tricorder.CLI.Daemon (restartDaemon, startDaemon, stopDaemon, waitForDaemon) import Tricorder.CLI.Operations (showDaemonInfo) import Tricorder.Daemon.DaemonInfo (DaemonInfo)-import Tricorder.Runtime (PidFile (..), SocketPath (..))+import Tricorder.Runtime.PidFile (PidFile)+import Tricorder.Runtime.SocketPath (SocketPath) import Tricorder.Socket.Client (isDaemonRunning) import Tricorder.Socket.UnixSocket (UnixSocket) @@ -26,7 +27,7 @@     :: ( Console :> es        , Daemons :> es        , Delay :> es-       , File :> es+       , Handles :> es        , IOE :> es        , Input DaemonInfo :> es        , Reader PidFile :> es
src/Tricorder/CLI/App/Test.hs view
@@ -3,7 +3,7 @@ import Atelier.Effects.Console (Console) import Atelier.Effects.Delay (Delay) import Atelier.Effects.Exit (Exit)-import Atelier.Effects.File (File)+import Atelier.Effects.Handles (Handles) import Atelier.Effects.Posix.Daemons (Daemons, PidFile) import Effectful (IOE) import Effectful.Reader.Static (Reader)@@ -20,11 +20,11 @@ import Tricorder.API.IfDaemonIsStopped qualified as IfDaemonIsStopped import Tricorder.API.Test.SuiteView.Schema qualified as SuiteView.Schema -import Tricorder.Build (BuildState (..))-import Tricorder.Runtime (SocketPath (..))+import Tricorder.Runtime.SocketPath (SocketPath (..)) import Tricorder.Socket.Client (queryStatus, queryStatusWait) import Tricorder.Socket.UnixSocket (UnixSocket) +import Tricorder.Build.State qualified as Build (State) import Tricorder.CLI.App.Test.Json qualified as Json import Tricorder.CLI.App.Test.Text qualified as Text import Tricorder.CLI.Daemon qualified as Daemons@@ -37,7 +37,7 @@        , Daemons :> es        , Delay :> es        , Exit :> es-       , File :> es+       , Handles :> es        , IOE :> es        , Reader PidFile :> es        , Reader SocketPath :> es@@ -61,7 +61,7 @@ showSuites     :: ( Daemons :> es        , Delay :> es-       , File :> es+       , Handles :> es        , IOE :> es        , Reader PidFile :> es        , Reader SocketPath :> es@@ -84,7 +84,7 @@                             $ Text.showSuites targets opts.testFilter selection                     JsonOutput ->                         pure-                            $ Json.wrapResponse+                            $ Json.wrapSuites selection                             $ Json.showBasePhase result                             $ Json.showSuites targets opts.testFilter selection   where@@ -104,11 +104,11 @@   awaitBuildStatus-    :: ( File :> es+    :: ( Handles :> es        , Reader SocketPath :> es        , UnixSocket :> es        )-    => IfBuildIsPending -> Eff es (Either Text BuildState)+    => IfBuildIsPending -> Eff es (Either Text Build.State) awaitBuildStatus wait = do     SocketPath sockPath <- Reader.ask     case wait of
src/Tricorder/CLI/App/Test/Json.hs view
@@ -1,42 +1,45 @@ module Tricorder.CLI.App.Test.Json     ( showSuites-    , wrapResponse+    , wrapSuites     , showBasePhase     , argumentError     ) where -import Data.Aeson (ToJSON, toJSON)-import Data.Aeson.Text (encodeToLazyText)+import Autodocodec (ValueCodec, nullCodec, toEncodingVia)+import Data.Aeson (toJSON)+import Data.Aeson.Encoding (encodingToLazyByteString)+import Tricorder.API.FieldMask.Projection (Projection)+import Tricorder.API.Response (MessageWithLoc (..), Response (..))+import Tricorder.API.Test.SuitesResponse (SuitesResponse (..)) import Tricorder.API.TestFilter (TestFilter)  import Data.Text qualified as T import Tricorder.API.FieldMask.Projection qualified as FieldMask.Projection import Tricorder.API.FieldMask.Schema qualified as FieldMask (Schema)+import Tricorder.API.Response qualified as Responses+import Tricorder.API.Test.SuitesResponse qualified as SuitesResponse -import Tricorder.Build-    ( BuildPhase (..)-    , BuildResult (..)-    , BuildState (..)-    , Diagnostic (..)-    , PostBuild (..)-    , Severity (..)-    )-import Tricorder.CLI.App.Test.Json.Responses-    ( MessageWithLoc (..)-    , Response (..)-    , SuitesResponse (..)-    ) import Tricorder.CLI.App.Test.SuiteView (selectSuites) import Tricorder.Session.TestTarget (TestTarget) +import Tricorder.Build.Diagnostic qualified as Build.Diagnostic+import Tricorder.Build.Phase qualified as Build.Phase+import Tricorder.Build.PostBuild qualified as Build.PostBuild+import Tricorder.Build.Result qualified as Build.Result+import Tricorder.Build.Severity qualified as Build.Severity+import Tricorder.Build.State qualified as Build (State)+import Tricorder.Build.State qualified as Build.State import Tricorder.Build.Test qualified as Test-import Tricorder.CLI.App.Test.Json.Responses qualified as Responses import Tricorder.Session.TestTarget qualified as TestTarget   showSuites-    :: [TestTarget] -> TestFilter -> FieldMask.Schema -> Test.Suites -> Response SuitesResponse+    :: [TestTarget]+    -> TestFilter+    -> FieldMask.Schema+    -> Test.Suites+    -> Response (SuitesResponse Projection) showSuites targets testFilter selection testSuites =     case selectSuites targets testFilter testSuites of         Left notFound ->@@ -45,32 +48,43 @@         Right suites -> Responses.Success $ SuitesResponse $ FieldMask.Projection.project selection . toJSON <$> suites  -wrapResponse :: (ToJSON a) => Response a -> Either Text Text-wrapResponse resp = case resp of-    Responses.Error _ -> Left $ toStrict $ encodeToLazyText resp-    _ -> Right $ toStrict $ encodeToLazyText resp+-- | Encode test suites projected down to the fields of the selection, in the+-- order they were selected in.+wrapSuites :: FieldMask.Schema -> Response (SuitesResponse Projection) -> Either Text Text+wrapSuites selection = wrapResponse $ SuitesResponse.codec $ FieldMask.Projection.codec selection  +wrapResponse :: ValueCodec a output -> Response a -> Either Text Text+wrapResponse payload resp = case resp of+    Responses.Error _ -> Left encoded+    _ -> Right encoded+  where+    encoded = decodeUtf8 $ encodingToLazyByteString $ toEncodingVia (Responses.codec payload) resp++ -- | Report invalid arguments given to a command. argumentError :: Text -> Either Text Text-argumentError err = wrapResponse @() $ Responses.Error $ MessageWithLoc "arguments" err+argumentError err = wrapResponse nullCodec $ Responses.Error $ MessageWithLoc "arguments" err  -showBasePhase :: Either Text BuildState -> (Test.Suites -> Response a) -> Response a+showBasePhase :: Either Text Build.State -> (Test.Suites -> Response a) -> Response a showBasePhase result mkResponse = case result of     Left err -> Responses.Error $ MessageWithLoc "build" err-    Right build -> case build.phase of-        Starting -> Responses.Pending $ MessageWithLoc "build" "starting"-        Building _ _ -> Responses.Pending $ MessageWithLoc "build" "building"-        PostBuilding _ postBuild+    Right build -> case Build.State.phase build of+        Build.Phase.Starting -> Responses.Pending $ MessageWithLoc "build" "starting"+        Build.Phase.Building _ _ -> Responses.Pending $ MessageWithLoc "build" "building"+        Build.Phase.PostBuilding _ postBuild             | Test.anyRunningTests postBuild.testSuites ->                 Responses.Pending $ MessageWithLoc "postBuild" "testing"             | otherwise -> mkResponse postBuild.testSuites-        Finished buildResult postBuild+        Build.Phase.Finished buildResult postBuild             | buildFailed buildResult postBuild ->                 Responses.Error $ MessageWithLoc "finished" "build failed before tests ran"             | otherwise -> mkResponse postBuild.testSuites-        Failed reason -> Responses.Error $ MessageWithLoc "build" $ "build failed: " <> reason+        Build.Phase.Failed reason -> Responses.Error $ MessageWithLoc "build" $ "build failed: " <> reason   where     buildFailed buildResult postBuild =-        postBuild.testSuites == mempty && any (\d -> d.severity >= SError) buildResult.diagnostics+        Build.PostBuild.testSuites postBuild == mempty+            && any+                (\d -> Build.Diagnostic.severity d >= Build.Severity.Error)+                (Build.Result.diagnostics buildResult)
− src/Tricorder/CLI/App/Test/Json/Responses.hs
@@ -1,79 +0,0 @@-module Tricorder.CLI.App.Test.Json.Responses-    ( Response (..)-    , MessageWithLoc (..)-    , SuitesResponse (..)-    )-where--import Atelier.Types.JSON.QuietSnake (QuietSnake (..))-import Data.Aeson-    ( FromJSON-    , Options (..)-    , SumEncoding (..)-    , ToJSON (..)-    , defaultOptions-    , genericToEncoding-    , genericToJSON-    , object-    , pairs-    , (.=)-    )-import Text.Casing (quietSnake)--import Tricorder.API.FieldMask.Projection qualified as FieldMask (Projection)---data Response a-    = Error MessageWithLoc-    | Pending MessageWithLoc-    | Success a-    deriving stock (Eq, Functor, Generic, Show)---instance Applicative Response where-    pure = Success-    Error message <*> _ = Error message-    _ <*> Error message = Error message-    Pending message <*> _ = Pending message-    _ <*> Pending message = Pending message-    Success f <*> Success a = Success $ f a---instance Monad Response where-    Error message >>= _ = Error message-    Pending message >>= _ = Pending message-    Success a >>= f = f a---instance (ToJSON a) => ToJSON (Response a) where-    toJSON = genericToJSON responseOptions-    toEncoding = genericToEncoding responseOptions---data MessageWithLoc = MessageWithLoc-    { location :: Text-    , message :: Text-    }-    deriving stock (Eq, Generic, Show)-    deriving (FromJSON, ToJSON) via QuietSnake MessageWithLoc---responseOptions :: Options-responseOptions =-    defaultOptions-        { constructorTagModifier = quietSnake-        , sumEncoding = ObjectWithSingleField-        }----- | Test suites, cut down to the requested fields.-newtype SuitesResponse = SuitesResponse-    { suites :: [FieldMask.Projection]-    }-    deriving stock (Eq, Show)----- | Written by hand so 'toEncoding' keeps the field order of the projection.-instance ToJSON SuitesResponse where-    toJSON response = object ["suites" .= response.suites]-    toEncoding response = pairs ("suites" .= response.suites)
src/Tricorder/CLI/App/Test/Text.hs view
@@ -13,18 +13,18 @@ import Tricorder.API.FieldMask.Schema qualified as FieldMask import Tricorder.API.TestFilter qualified as TestFilter -import Tricorder.Build-    ( BuildPhase (..)-    , BuildProgress (..)-    , BuildResult (..)-    , BuildState (..)-    , Diagnostic (..)-    , PostBuild (..)-    , Severity (..)-    )+import Tricorder.Build.Diagnostic (Diagnostic (..)) import Tricorder.CLI.App.Test.SuiteView (selectSuites) import Tricorder.Session.TestTarget (TestTarget) +import Tricorder.Build.Phase qualified as Build (Phase)+import Tricorder.Build.Phase qualified as Build.Phase+import Tricorder.Build.PostBuild qualified as Build.PostBuild+import Tricorder.Build.Progress qualified as Build.Progress+import Tricorder.Build.Result qualified as Build.Result+import Tricorder.Build.Severity qualified as Build.Severity+import Tricorder.Build.State qualified as Build (State)+import Tricorder.Build.State qualified as Build.State import Tricorder.Build.Test qualified as Test import Tricorder.Session.TestTarget qualified as TestTarget @@ -45,16 +45,16 @@                 $ FieldMask.Projection.project selection . toJSON <$> suites  -wrapTextShow :: Either Text BuildState -> (BuildPhase -> Either Text Text) -> Either Text Text+wrapTextShow :: Either Text Build.State -> (Build.Phase -> Either Text Text) -> Either Text Text wrapTextShow = \case     Left err -> const $ Left $ "Error: " <> err     Right build -> ($ build.phase)  -showBasePhase :: (Test.Suites -> Either Text Text) -> BuildPhase -> Either Text Text+showBasePhase :: (Test.Suites -> Either Text Text) -> Build.Phase -> Either Text Text showBasePhase showTests = \case-    Starting -> Right "Starting..."-    Building _ progress ->+    Build.Phase.Starting -> Right "Starting..."+    Build.Phase.Building _ progress ->         Right             $ mconcat                 [ "Building ("@@ -63,22 +63,23 @@                 , show progress.total                 , ")..."                 ]-    PostBuilding result postBuild+    Build.Phase.PostBuilding result postBuild         | buildFailed result postBuild ->             Left $ "build failed before tests ran"         | Test.anyRunningTests postBuild.testSuites ->             Right $ showTestProgress postBuild.testSuites         | otherwise ->             showTests postBuild.testSuites-    Finished result postBuild+    Build.Phase.Finished result postBuild         | buildFailed result postBuild ->             Left "build failed before tests ran"         | otherwise ->             showTests postBuild.testSuites-    Failed err -> Left $ "Build failed: " <> err+    Build.Phase.Failed err -> Left $ "Build failed: " <> err   where     buildFailed result postBuild =-        postBuild.testSuites == mempty && any (\d -> d.severity >= SError) result.diagnostics+        postBuild.testSuites == mempty+            && any (\d -> d.severity >= Build.Severity.Error) result.diagnostics   showTestProgress :: Test.Suites -> Text
src/Tricorder/CLI/Arguments.hs view
@@ -1,4 +1,4 @@-module Tricorder.CLI.Arguments (reader) where+module Tricorder.CLI.Arguments (reader, opts) where  import Atelier.Effects.Arguments (Arguments) import Effectful.Reader.Static (Reader)
src/Tricorder/CLI/Daemon.hs view
@@ -7,7 +7,7 @@ where  import Atelier.Effects.Delay (Delay)-import Atelier.Effects.File (File)+import Atelier.Effects.Handles (Handles) import Atelier.Effects.Posix.Daemons (Daemons) import Atelier.Effects.Timeout (Timeout) import Atelier.Time (Millisecond, Second)@@ -23,7 +23,8 @@ import Atelier.Effects.Timeout qualified as Timeout import Tricorder.API.IfThereArePendingQueries qualified as IfThereArePendingQueries -import Tricorder.Runtime (PidFile, SocketPath (..))+import Tricorder.Runtime.PidFile (PidFile)+import Tricorder.Runtime.SocketPath (SocketPath (..)) import Tricorder.Socket.Client (isDaemonReady, isDaemonRunning, requestShutdown) import Tricorder.Socket.UnixSocket (UnixSocket) @@ -47,7 +48,7 @@ stopDaemon     :: ( Daemons :> es        , Delay :> es-       , File :> es+       , Handles :> es        , Reader PidFile :> es        , Reader SocketPath :> es        , Timeout :> es@@ -107,7 +108,7 @@ restartDaemon     :: ( Daemons :> es        , Delay :> es-       , File :> es+       , Handles :> es        , IOE :> es        , Reader PidFile :> es        , Reader SocketPath :> es
+ src/Tricorder/CLI/Docs.hs view
@@ -0,0 +1,65 @@+module Tricorder.CLI.Docs (renderReference) where++import Options.Applicative+    ( ParserInfo (..)+    , ParserResult (..)+    , columns+    , execParserPure+    , prefs+    , renderFailure+    )+import Options.Applicative.Common (mapParser)+import Options.Applicative.Types (OptReader (..), Option (..))++import Data.Text qualified as Text++import Tricorder.CLI.Arguments (opts)+++-- | Markdown reference: one section per command (depth-first), each containing+-- the verbatim @--help@ output.+renderReference :: Text+renderReference =+    Text.intercalate "\n" $ section <$> commandPaths+++section :: ([String], String) -> Text+section (path, help) =+    Text.unlines+        [ "### `" <> Text.unwords (map toText ("tricorder" : path)) <> " --help`"+        , ""+        , "```"+        , Text.stripEnd (toText help)+        , "```"+        ]+++-- | A parser info with its result type hidden; subcommands have their own.+data SomeInfo = forall x. SomeInfo (ParserInfo x)+++-- | All command paths (the root is @[]@), paired with their rendered help.+commandPaths :: [([String], String)]+commandPaths = go [] (SomeInfo opts)+  where+    go path (SomeInfo info) =+        (path, helpFor path)+            : concatMap+                (\(name, child) -> go (path <> [name]) child)+                (subcommands info)+++subcommands :: ParserInfo a -> [(String, SomeInfo)]+subcommands info = concat $ mapParser (const cmds) info.infoParser+  where+    cmds :: Option x -> [(String, SomeInfo)]+    cmds opt = case opt.optMain of+        CmdReader _ cs -> [(name, SomeInfo child) | (name, child) <- reverse cs]+        _ -> []+++helpFor :: [String] -> String+helpFor path =+    case execParserPure (prefs (columns 80)) opts (path <> ["--help"]) of+        Failure failure -> fst $ renderFailure failure "tricorder"+        _ -> ""
src/Tricorder/CLI/Main.hs view
@@ -5,6 +5,7 @@ import Data.Default (def) import Effectful (runEff) import Effectful.Concurrent (runConcurrent)+import Effectful.FileSystem.IO (stderr) import Effectful.Provider (provideWith_, runProvider_)  import Atelier.Effects.Arguments qualified as Arguments@@ -14,19 +15,18 @@ import Atelier.Effects.Delay qualified as Delay import Atelier.Effects.Env qualified as Env import Atelier.Effects.Exit qualified as Exit-import Atelier.Effects.File qualified as File-import Atelier.Effects.FileSystem qualified as FileSystem import Atelier.Effects.FileSystem.Glob qualified as Glob+import Atelier.Effects.Handles qualified as Handles import Atelier.Effects.Input qualified as Input import Atelier.Effects.Log qualified as Log import Atelier.Effects.Posix.Daemons qualified as Daemons import Atelier.Effects.Process qualified as Process import Atelier.Effects.Timeout qualified as Timeout+import Effectful.FileSystem qualified as FileSystem  import Tricorder.CLI.UI.Brick (runBrick) import Tricorder.CLI.UI.BrickChan (runBrickChan) import Tricorder.Config (asInput)-import Tricorder.Runtime (runLogPath, runPidFile, runProjectRoot, runRuntimeDir, runSocketPath) import Tricorder.Session.CabalFile (inputCabalFiles)  import Tricorder.CLI.App qualified as App@@ -34,6 +34,13 @@ import Tricorder.CLI.UI.Keys qualified as Keys import Tricorder.Config.LoadedConfig qualified as LoadedConfig import Tricorder.Daemon.DaemonInfo qualified as DaemonInfo+import Tricorder.Runtime.Cache qualified as Runtime.Cache+import Tricorder.Runtime.Directory qualified as Runtime.Directory+import Tricorder.Runtime.LogPath qualified as Runtime.LogPath+import Tricorder.Runtime.PidFile qualified as Runtime.PidFile+import Tricorder.Runtime.ProjectHash qualified as Runtime.ProjectHash+import Tricorder.Runtime.ProjectRoot qualified as Runtime.ProjectRoot+import Tricorder.Runtime.SocketPath qualified as Runtime.SocketPath import Tricorder.Session qualified as Session import Tricorder.Session.StackProject qualified as StackProject import Tricorder.Socket.UnixSocket qualified as UnixSocket@@ -45,6 +52,8 @@ main :: IO () main =     runEff+        . Arguments.runIO+        . CLI.Arguments.reader         . Timeout.run         . runConcurrent         . Conc.runIO@@ -55,25 +64,25 @@         . Exit.runIO         . Clock.runIO         . Delay.runIO-        . File.run-        . FileSystem.runIO+        . Handles.run+        . FileSystem.runFileSystem         . Glob.runIO-        . runProjectRoot-        . runRuntimeDir-        . runPidFile-        . runSocketPath-        . runLogPath+        . Env.runIO+        . Runtime.ProjectRoot.asReader+        . Runtime.ProjectHash.asReader+        . Runtime.Cache.asReader+        . Log.runToHandle stderr Log.INFO+        . Runtime.Directory.asReader+        . Runtime.PidFile.asReader+        . Runtime.SocketPath.asReader+        . Runtime.LogPath.asReader         . LoadedConfig.asInput         . LoadedConfig.asNestedInput @"keybindings" @Keys.Config         . Input.map (either @_ @Keys.Config (const def) id)         . Input.toReader @Keys.Config         . Daemons.run         . Process.run-        . Arguments.runIO-        . CLI.Arguments.reader         . UnixSocket.runIO-        . Env.runIO-        . Log.runNoOp         . StackProject.inputWithCache         . inputCabalFiles         . Tricorder.Config.asInput@@ -90,7 +99,7 @@                         . GhcPkg.runGhcPkgIO                         . PackageStore.run                         . Hackage.run-                        . DaemonInfo.runInput+                        . DaemonInfo.asInput                         $ do                             installTerminationHandler                             App.run
src/Tricorder/CLI/Operations.hs view
@@ -10,13 +10,13 @@ import Atelier.Effects.Clock (Clock, currentTimeZone) import Atelier.Effects.Console (Console) import Atelier.Effects.Exit (Exit)-import Atelier.Effects.File (File)-import Atelier.Effects.FileSystem (FileSystem, doesFileExist, readFileLbs)+import Atelier.Effects.Handles (Handles) import Atelier.Effects.Input (Input, input) import Atelier.Effects.Log (Log) import Data.Aeson (ToJSON, encode) import Data.Time.Format (defaultTimeLocale, formatTime) import Data.Time.LocalTime (utcToLocalTime)+import Effectful.FileSystem (FileSystem) import Effectful.Provider (Provider_, provideWith_) import Effectful.Reader.Static (Reader, ask) import Tricorder.API.Command@@ -31,18 +31,25 @@  import Atelier.Effects.Console qualified as Console import Atelier.Effects.Exit qualified as Exit+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path import Data.ByteString.Lazy qualified as BSL import Data.Map.Strict qualified as Map import Data.Text qualified as T import Tricorder.API.IfBuildIsPending qualified as IfBuildIsPending -import Tricorder.Build (BuildState (..), Severity (..))+import Tricorder.Build.Diagnostic (Diagnostic (..)) import Tricorder.Build.Duration (Duration (..))+import Tricorder.Build.PostBuild (PostBuild (..))+import Tricorder.Build.Result (Result (..))+import Tricorder.Build.State (State (..)) import Tricorder.Build.Test (Suites (..)) import Tricorder.CLI.Render (diagnosticLineIndexed, formatDuration, renderSourceResults) import Tricorder.Daemon.DaemonInfo (DaemonInfo (..))-import Tricorder.Runtime (SocketPath (..))+import Tricorder.Runtime.LogPath (LogPath (..))+import Tricorder.Runtime.SocketPath (SocketPath (..)) import Tricorder.Session.CabalFile (CabalFile)+import Tricorder.Session.Util (indent) import Tricorder.Socket.Client (queryStatus, queryStatusWait) import Tricorder.Socket.UnixSocket (UnixSocket) import Tricorder.SourceLookup (lookupModuleSource, projectSourceDirs)@@ -51,12 +58,14 @@ import Tricorder.SourceLookup.PackageStore (PackageStore) import Tricorder.TestOutput (stripGhciNoise) -import Tricorder.Build qualified as Build import Tricorder.Build.EvalComment qualified as Eval+import Tricorder.Build.Phase qualified as Build.Phase+import Tricorder.Build.Severity qualified as Severity+import Tricorder.Build.State qualified as Build (State (..)) import Tricorder.Build.Test qualified as Test import Tricorder.Build.Test qualified as Tests+import Tricorder.Session qualified as Session import Tricorder.Session.Stage.Build.Session qualified as Build (Session)-import Tricorder.Session.Target qualified as Target import Tricorder.Session.TestTarget qualified as TestTarget  @@ -72,7 +81,7 @@     :: ( Clock :> es        , Console :> es        , Exit :> es-       , File :> es+       , Handles :> es        , Provider_ Console Console.Output :> es        , Reader SocketPath :> es        , UnixSocket :> es@@ -93,10 +102,10 @@                     renderText opts.verbosity opts.expand state   where     renderText verbosity expand state = case state.phase of-        Build.Starting -> Console.putStrLn "Building..."-        Build.Building _ _ -> Console.putStrLn "Building..."-        Build.Failed msg -> reportBuildFailed msg-        Build.PostBuilding _ postBuild ->+        Build.Phase.Starting -> Console.putStrLn "Building..."+        Build.Phase.Building _ _ -> Console.putStrLn "Building..."+        Build.Phase.Failed msg -> reportBuildFailed msg+        Build.Phase.PostBuilding _ postBuild ->             let                 testsRunning = Test.anyRunningTests postBuild.testSuites                 commentsEvaluating = Eval.phasePending postBuild.evalComments@@ -110,7 +119,7 @@                         Console.putStrLn "Evaluating comments..."                     | otherwise ->                         Console.putStrLn "Post-procesing..."-        Build.Finished result postBuild -> do+        Build.Phase.Finished result postBuild -> do             tz <- currentTimeZone             case expand of                 Just n ->@@ -153,10 +162,10 @@             (Concise, firstLine : _ : _) -> firstLine <> " (use --verbose to see the full message)"             _ -> message -    buildHasErrors r = any ((== SError) . (.severity)) r.diagnostics+    buildHasErrors r = any ((== Severity.Error) . (.severity)) r.diagnostics     buildSummary tz r =-        let errs = length $ filter ((== SError) . (.severity)) r.diagnostics-            warns = length $ filter ((== SWarning) . (.severity)) r.diagnostics+        let errs = length $ filter ((== Severity.Error) . (.severity)) r.diagnostics+            warns = length $ filter ((== Severity.Warning) . (.severity)) r.diagnostics             ts = toText $ "— " <> formatTime defaultTimeLocale "%H:%M:%S" (utcToLocalTime tz r.completedAt)             stats =                 toText $ "(" <> show r.moduleCount <> " modules, " <> formatDuration r.duration.getDuration <> ")"@@ -184,16 +193,12 @@     isFailedCase _ = False  -showLog-    :: ( Console :> es-       , FileSystem :> es-       )-    => FilePath -> Eff es ()+showLog :: (Console :> es, FileSystem :> es) => Path.Absolute -> Eff es () showLog path = do-    exists <- doesFileExist path+    exists <- File.exists path     if not exists         then Console.putTextLn $ "Log file does not exist yet: " <> toText path-        else readFileLbs path >>= Console.putStr . BSL.toStrict+        else File.read path >>= Console.putStr   showSource@@ -223,7 +228,7 @@ showEvalComments     :: ( Console :> es        , Exit :> es-       , File :> es+       , Handles :> es        , Reader SocketPath :> es        , UnixSocket :> es        )@@ -243,14 +248,14 @@     JsonOutput -> json   where     text = do-        Console.putTextLn "Targets:"-        for_ daemonInfo.targets \target ->-            Console.putTextLn $ "- " <> Target.render target-        Console.putTextLn "Watch directories:"-        for_ daemonInfo.watchDirs \dir ->-            Console.putTextLn $ "- " <> toText dir-        Console.putTextLn $ "Socket file path: " <> toText daemonInfo.sockPath-        Console.putTextLn $ "Log file path: " <> toText daemonInfo.logFile+        Console.putTextLn+            $ T.intercalate+                "\n"+                [ "Session:"+                , indent $ Session.display daemonInfo.session+                , "Socket file path: " <> toText daemonInfo.sockPath.getSocketPath+                , "Log file path: " <> toText daemonInfo.logFile.getLogPath+                ]     json = putJson daemonInfo  @@ -258,17 +263,17 @@     :: ( Console :> es        , Exit :> es        )-    => Either Text BuildState -> Eff es ()+    => Either Text Build.State -> Eff es () displayTextOutput = \case     Left err -> do         Console.putTextLn $ "Error: " <> err         Exit.failure-    Right (BuildState phase _) -> case phase of-        Build.Starting -> Console.putStrLn "Starting..."-        Build.Building _ _ -> Console.putStrLn "Building..."-        Build.PostBuilding _ postBuild -> txtEvalComments postBuild-        Build.Finished _ postBuild -> txtEvalComments postBuild-        Build.Failed err -> do+    Right (Build.State phase _) -> case phase of+        Build.Phase.Starting -> Console.putStrLn "Starting..."+        Build.Phase.Building _ _ -> Console.putStrLn "Building..."+        Build.Phase.PostBuilding _ postBuild -> txtEvalComments postBuild+        Build.Phase.Finished _ postBuild -> txtEvalComments postBuild+        Build.Phase.Failed err -> do             Console.putTextLn $ "Error: " <> err             Exit.failure   where@@ -313,19 +318,19 @@                     ]  -displayJsonOutput :: (Console :> es, Exit :> es) => Either Text BuildState -> Eff es ()+displayJsonOutput :: (Console :> es, Exit :> es) => Either Text Build.State -> Eff es () displayJsonOutput = \case     Left err -> do         putJson $ Eval.Failed err         Exit.failure-    Right (BuildState phase _) -> case phase of-        Build.Starting -> putJson Eval.Starting-        Build.Building _ _ -> putJson Eval.Building-        Build.Failed msg -> do+    Right (Build.State phase _) -> case phase of+        Build.Phase.Starting -> putJson Eval.Starting+        Build.Phase.Building _ _ -> putJson Eval.Building+        Build.Phase.Failed msg -> do             putJson $ Eval.Failed msg             Exit.failure-        Build.PostBuilding _ postBuild -> jsonEvalComments postBuild-        Build.Finished _ postBuild -> jsonEvalComments postBuild+        Build.Phase.PostBuilding _ postBuild -> jsonEvalComments postBuild+        Build.Phase.Finished _ postBuild -> jsonEvalComments postBuild   where     jsonEvalComments postBuild = case postBuild.evalComments of         Eval.Looking -> putJson Eval.Evaluating@@ -341,7 +346,7 @@  displayPendingBuildStatus     :: ( Console :> es-       , File :> es+       , Handles :> es        , Reader SocketPath :> es        , UnixSocket :> es        )@@ -350,11 +355,11 @@     SocketPath sockPath <- ask     current <- queryStatus sockPath     case current of-        Right BuildState {phase = Build.Starting} -> Console.putStrLn "Starting..."-        Right BuildState {phase = Build.Building _ _} -> Console.putStrLn "Building..."-        Right BuildState {phase = Build.Finished _ postBuild} -> displayPostBuildStatus postBuild-        Right BuildState {phase = Build.PostBuilding _ postBuild} -> displayPostBuildStatus postBuild-        Right BuildState {phase = Build.Failed _} -> pure ()+        Right Build.State {phase = Build.Phase.Starting} -> Console.putStrLn "Starting..."+        Right Build.State {phase = Build.Phase.Building _ _} -> Console.putStrLn "Building..."+        Right Build.State {phase = Build.Phase.Finished _ postBuild} -> displayPostBuildStatus postBuild+        Right Build.State {phase = Build.Phase.PostBuilding _ postBuild} -> displayPostBuildStatus postBuild+        Right Build.State {phase = Build.Phase.Failed _} -> pure ()         Left _ -> pure ()   where     displayPostBuildStatus postBuild@@ -370,11 +375,11 @@   awaitBuildStatus-    :: ( File :> es+    :: ( Handles :> es        , Reader SocketPath :> es        , UnixSocket :> es        )-    => IfBuildIsPending -> Eff es (Either Text BuildState)+    => IfBuildIsPending -> Eff es (Either Text Build.State) awaitBuildStatus wait = do     SocketPath sockPath <- ask     case wait of
src/Tricorder/CLI/Render.hs view
@@ -17,9 +17,12 @@ import Atelier.Effects.Console qualified as Console import Tricorder.SourceLookup.ModuleSourceResult qualified as ModuleSourceResult -import Tricorder.Build (Diagnostic (..), Severity (..))+import Tricorder.Build.Diagnostic (Diagnostic (..)) +import Tricorder.Build.Diagnostic qualified as Build (Diagnostic)+import Tricorder.Build.Severity qualified as Severity + formatDuration :: Millisecond -> Text formatDuration d =     let ms = toMicroseconds d `div` 1000@@ -33,23 +36,23 @@ -- | Single-line diagnostic for plain-text / shell output. -- -- Format: @E src\/Foo\/Bar.hs:42 \`something\` not in scope@-diagnosticLine :: Diagnostic -> Text+diagnosticLine :: Build.Diagnostic -> Text diagnosticLine d =     prefix d.severity <> " " <> toText d.file <> ":" <> show d.line <> " " <> d.title   where-    prefix SError = "E"-    prefix SWarning = "W"+    prefix Severity.Error = "E"+    prefix Severity.Warning = "W"   -- | Like 'diagnosticLine' but prefixed with a 1-based index. -- -- Format: @[N] E src\/Foo\/Bar.hs:42 \`something\` not in scope@-diagnosticLineIndexed :: Int -> Diagnostic -> Text+diagnosticLineIndexed :: Int -> Build.Diagnostic -> Text diagnosticLineIndexed n d = "[" <> show n <> "] " <> diagnosticLine d   -- | One-liner followed by the full GHC message body (verbose mode).-diagnosticBlock :: Diagnostic -> Text+diagnosticBlock :: Build.Diagnostic -> Text diagnosticBlock d = diagnosticLine d <> "\n" <> d.text  
src/Tricorder/CLI/UI.hs view
@@ -8,7 +8,7 @@ import Atelier.Effects.Console (Console) import Atelier.Effects.Delay (Delay) import Atelier.Effects.Exit (Exit)-import Atelier.Effects.File (File)+import Atelier.Effects.Handles (Handles) import Atelier.Effects.Process (Process, getExecutablePath, proc, runProcess) import Brick (App (..), EventM, neverShowCursor) import Brick.BChan (BChan, writeBChanNonBlocking)@@ -19,6 +19,9 @@ import Effectful.Reader.Static (Reader, ask)  import Atelier.Effects.Conc qualified as Conc+import Tricorder.API.Command qualified as Command+import Tricorder.API.Daemon.Command qualified as Daemon.Command+import Tricorder.API.IfThereArePendingQueries qualified as IfThereArePendingQueries  import Tricorder.CLI.Daemon (waitForDaemon) import Tricorder.CLI.UI.Brick (Brick)@@ -27,7 +30,7 @@ import Tricorder.CLI.UI.Keys (KeyEvent, mkDispatcher) import Tricorder.CLI.UI.State (State (..), Viewports (..)) import Tricorder.CLI.UI.View (mkAttrMap, view)-import Tricorder.Runtime (SocketPath (..))+import Tricorder.Runtime.SocketPath (SocketPath (..)) import Tricorder.Socket.Client (queryWatch) import Tricorder.Socket.UnixSocket (UnixSocket) @@ -49,7 +52,7 @@        , Console :> es        , Delay :> es        , Exit :> es-       , File :> es+       , Handles :> es        , Process :> es        , Reader Keys.Config :> es        , Reader SocketPath :> es@@ -108,7 +111,13 @@             self <- getExecutablePath             -- Swallow failures: a restart that errors must not take down the TUI, and             -- the flag has to be cleared either way.-            _ <- trySync $ runProcess $ proc self ["restart"]+            _ <-+                trySync+                    $ runProcess+                    $ proc self+                    $ Command.toArgs+                    $ Command.Daemon+                    $ Daemon.Command.Restart IfThereArePendingQueries.DontWait             void waitForDaemon  
src/Tricorder/CLI/UI/Event.hs view
@@ -10,14 +10,15 @@  import Graphics.Vty qualified as Vty -import Tricorder.Build (BuildState (..)) import Tricorder.CLI.UI.Keys (KeyEvent) import Tricorder.CLI.UI.State (Processed (..), State (..), Viewports (..)) import Tricorder.Socket.Client (Restarting (..)) +import Tricorder.Build.State qualified as Build (State) + data Event-    = NewBuildState (Either Restarting BuildState)+    = NewBuildState (Either Restarting Build.State)     | FailedBuild Text  
src/Tricorder/CLI/UI/State.hs view
@@ -17,9 +17,9 @@ import Atelier.Effects.Clock qualified as Clock import Tricorder.API.TestFilter qualified as TestFilter -import Tricorder.Build (BuildState) import Tricorder.CLI.UI.Route (Route) +import Tricorder.Build.State qualified as Build (State) import Tricorder.CLI.UI.Route qualified as Route  @@ -32,7 +32,7 @@   data State = State-    { buildState :: Processed Text BuildState+    { buildState :: Processed Text Build.State     , timeZone :: TimeZone     , route :: Route     , testFilter :: TestFilter
src/Tricorder/CLI/UI/View.hs view
@@ -35,8 +35,13 @@ import Graphics.Vty.Attributes.Color qualified as Color import Tricorder.API.TestFilter qualified as TestFilter -import Tricorder.Build (BuildPhase, BuildResult, BuildState, Diagnostic, Severity (..))+import Tricorder.Build.Diagnostic (Diagnostic (..)) import Tricorder.Build.Duration (Duration (..))+import Tricorder.Build.PostBuild (PostBuild (..))+import Tricorder.Build.Progress (Progress (..))+import Tricorder.Build.Result (Result (..))+import Tricorder.Build.Severity (Severity)+import Tricorder.Build.State (State (..)) import Tricorder.CLI.UI.Keys (KeyEvent, viewKeybindings) import Tricorder.CLI.UI.Misc (emphasis, err, hBoxSpaced, ok, subtle, vBoxSpaced, warn) import Tricorder.CLI.UI.Route (Route)@@ -49,15 +54,21 @@ import Tricorder.Session.TestTarget (TestTarget) import Tricorder.TestOutput (stripGhciNoise) -import Tricorder.Build qualified as Build+import Tricorder.Build.Diagnostic qualified as Build (Diagnostic) import Tricorder.Build.EvalComment qualified as Eval+import Tricorder.Build.Phase qualified as Build (Phase)+import Tricorder.Build.Phase qualified as Build.Phase+import Tricorder.Build.Result qualified as Build (Result)+import Tricorder.Build.Severity qualified as Severity+import Tricorder.Build.State qualified as Build (State) import Tricorder.Build.Test qualified as Test import Tricorder.CLI.UI.Keys qualified as Keys import Tricorder.CLI.UI.Route qualified as Route+import Tricorder.CLI.UI.State qualified as UI (State) import Tricorder.Session.TestTarget qualified as TestTarget  -mkAttrMap :: State -> AttrMap+mkAttrMap :: UI.State -> AttrMap mkAttrMap =     const         ( attrMap@@ -71,7 +82,7 @@         )  -view :: KeyConfig KeyEvent -> KeyDispatcher KeyEvent m -> State -> [Widget Viewports]+view :: KeyConfig KeyEvent -> KeyDispatcher KeyEvent m -> UI.State -> [Widget Viewports] view kc dispatcher ws =     [ vBoxSpaced         1@@ -89,12 +100,12 @@     ]  -viewTabs :: State -> Widget n+viewTabs :: UI.State -> Widget n viewTabs ws =     hBoxSpaced 1 $ viewRouteTab ws <$> universe @Route  -viewRouteTab :: State -> Route -> Widget n+viewRouteTab :: UI.State -> Route -> Widget n viewRouteTab ws route =     style $ txt $ brackets $ Route.name route   where@@ -102,15 +113,15 @@     style = if route == currentRoute ws then id else subtle  -viewTests :: State -> Widget Viewports+viewTests :: UI.State -> Widget Viewports viewTests ws = withBuildState ws (viewTestResultsPanel ws)  -viewEvals :: State -> Widget Viewports+viewEvals :: UI.State -> Widget Viewports viewEvals ws = withBuildState ws $ viewEvalCommentsPanel ws  -viewMain :: State -> Widget Viewports+viewMain :: UI.State -> Widget Viewports viewMain ws = withBuildState ws (viewDefaultPanel ws.timeZone)  @@ -122,7 +133,7 @@     handlers = (.khHandler) . snd <$> keyDispatcherToList dispatcher  -withBuildState :: State -> (BuildState -> Widget Viewports) -> Widget Viewports+withBuildState :: UI.State -> (Build.State -> Widget Viewports) -> Widget Viewports withBuildState ws render =     case ws.buildState of         Waiting ->@@ -133,7 +144,7 @@             render bs  -viewAppHeader :: KeyConfig KeyEvent -> State -> Widget n+viewAppHeader :: KeyConfig KeyEvent -> UI.State -> Widget n viewAppHeader kc ws =     hBoxSpaced         1@@ -149,7 +160,7 @@         ]  -viewHelpHint :: KeyConfig KeyEvent -> State -> Widget n+viewHelpHint :: KeyConfig KeyEvent -> UI.State -> Widget n viewHelpHint kc state     | state.showHelp = subtle $ txt $ "Press " <> exitHelpStr <> " to go back"     | state.route == Route.Tests =@@ -167,7 +178,7 @@         (pre, post) -> T.intercalate ", " pre <> " " <> andOr <> " " <> T.intercalate ", " post  -viewHeading :: State -> Maybe Text+viewHeading :: UI.State -> Maybe Text viewHeading ws     | ws.showHelp = Just "Help"     | otherwise = case currentRoute ws of@@ -178,11 +189,11 @@         Route.Evals -> Just "Eval comments"  -viewDefaultPanel :: TimeZone -> BuildState -> Widget Viewports+viewDefaultPanel :: TimeZone -> Build.State -> Widget Viewports viewDefaultPanel tz bs = viewBuildPhase tz bs.phase  -viewTestResultsPanel :: State -> BuildState -> Widget Viewports+viewTestResultsPanel :: UI.State -> Build.State -> Widget Viewports viewTestResultsPanel ws bs =     vBoxSpaced         1@@ -191,14 +202,14 @@         ]  -viewEvalCommentsPanel :: State -> BuildState -> Widget Viewports+viewEvalCommentsPanel :: UI.State -> Build.State -> Widget Viewports viewEvalCommentsPanel ws bs =     vBoxSpaced         1         [ viewBuildPhaseLine ws.timeZone bs.phase         , case bs.phase of-            Build.Finished _ postBuild -> viewEvalComments postBuild.evalComments-            Build.PostBuilding _ postBuild -> viewEvalComments postBuild.evalComments+            Build.Phase.Finished _ postBuild -> viewEvalComments postBuild.evalComments+            Build.Phase.PostBuilding _ postBuild -> viewEvalComments postBuild.evalComments             _ -> txt "Waiting for build..."         ] @@ -234,29 +245,29 @@                     ]  -viewBuildPhase :: TimeZone -> BuildPhase -> Widget Viewports+viewBuildPhase :: TimeZone -> Build.Phase -> Widget Viewports viewBuildPhase tz = \case-    Build.Starting ->+    Build.Phase.Starting ->         warn $ txt "Starting..."-    Build.Building testTargets phase ->+    Build.Phase.Building testTargets progress ->         vBoxSpaced             1-            [ warn $ txt $ "Building (" <> show phase.compiled <> "/" <> show phase.total <> ")..."+            [ warn $ txt $ "Building (" <> show progress.compiled <> "/" <> show progress.total <> ")..."             , viewPendingTestTargets testTargets             ]-    Build.PostBuilding result postBuild ->+    Build.Phase.PostBuilding result postBuild ->         vBoxSpaced             1             [ viewBuildResult tz result             , viewTestRuns postBuild.testSuites             ]-    Build.Finished result postBuild ->+    Build.Phase.Finished result postBuild ->         vBoxSpaced             1             [ viewBuildResult tz result             , viewTestRuns postBuild.testSuites             ]-    Build.Failed msg ->+    Build.Phase.Failed msg ->         viewBuildFailed msg  @@ -286,7 +297,7 @@         . viewport vp Vertical  -viewBuildResult :: TimeZone -> BuildResult -> Widget Viewports+viewBuildResult :: TimeZone -> Build.Result -> Widget Viewports viewBuildResult tz result     | null result.diagnostics =         hBoxSpaced@@ -297,8 +308,8 @@             ]     | otherwise =         let msgs = result.diagnostics-            errCount = length $ filter (\m -> m.severity == SError) msgs-            warnCount = length $ filter (\m -> m.severity == SWarning) msgs+            errCount = length $ filter (\d -> d.severity == Severity.Error) msgs+            warnCount = length $ filter (\d -> d.severity == Severity.Warning) msgs             header =                 if errCount > 0                     then@@ -317,26 +328,26 @@                 ]  -viewDiagnostic :: Diagnostic -> Widget n+viewDiagnostic :: Build.Diagnostic -> Widget n viewDiagnostic m =     vBox         [ hBoxSpaced             1             [ severityLabel-            , txt $ toText loc+            , txt loc             ]         , txtWrap m.text         ]   where-    loc = m.file <> ":" <> show m.line <> ":" <> show m.col+    loc = toText m.file <> ":" <> show m.line <> ":" <> show m.col     severityLabel = withDefAttr (severityToAttrName m.severity) $ txt $ case m.severity of-        SError -> "error:"-        SWarning -> "warning:"+        Severity.Error -> "error:"+        Severity.Warning -> "warning:"   severityToAttrName :: Severity -> AttrName-severityToAttrName SError = attrName "error"-severityToAttrName SWarning = attrName "warning"+severityToAttrName Severity.Error = attrName "error"+severityToAttrName Severity.Warning = attrName "warning"   viewDuration :: Duration -> Widget n@@ -405,21 +416,21 @@  -- | Single-line build status with no scrollable diagnostics list, used as a -- compact header when a secondary panel (test results) is open.-viewBuildPhaseLine :: TimeZone -> BuildPhase -> Widget n+viewBuildPhaseLine :: TimeZone -> Build.Phase -> Widget n viewBuildPhaseLine tz = \case-    Build.Starting ->+    Build.Phase.Starting ->         warn $ txt "Starting..."-    Build.Building _ phase ->+    Build.Phase.Building _ phase ->         warn $ txt $ "Building (" <> show phase.compiled <> "/" <> show phase.total <> ")..."-    Build.PostBuilding result _ ->+    Build.Phase.PostBuilding result _ ->         viewBuildResultLine tz result-    Build.Finished result _ ->+    Build.Phase.Finished result _ ->         viewBuildResultLine tz result-    Build.Failed _ ->+    Build.Phase.Failed _ ->         err $ txt "Build command failed"  -viewBuildResultLine :: TimeZone -> BuildResult -> Widget n+viewBuildResultLine :: TimeZone -> Build.Result -> Widget n viewBuildResultLine tz result     | null result.diagnostics =         hBoxSpaced@@ -429,8 +440,8 @@             , viewTimestamp tz result.completedAt             ]     | otherwise =-        let errCount = length $ filter (\m -> m.severity == SError) result.diagnostics-            warnCount = length $ filter (\m -> m.severity == SWarning) result.diagnostics+        let errCount = length $ filter (\m -> m.severity == Severity.Error) result.diagnostics+            warnCount = length $ filter (\m -> m.severity == Severity.Warning) result.diagnostics             header =                 if errCount > 0                     then@@ -440,9 +451,9 @@         in  hBoxSpaced 1 [header, viewDuration result.duration, viewTimestamp tz result.completedAt]  -phaseTestRuns :: BuildPhase -> Test.Suites-phaseTestRuns (Build.PostBuilding _ postBuild) = postBuild.testSuites-phaseTestRuns (Build.Finished _ postBuild) = postBuild.testSuites+phaseTestRuns :: Build.Phase -> Test.Suites+phaseTestRuns (Build.Phase.PostBuilding _ postBuild) = postBuild.testSuites+phaseTestRuns (Build.Phase.Finished _ postBuild) = postBuild.testSuites phaseTestRuns _ = Test.Suites mempty  
src/Tricorder/Config/LoadedConfig.hs view
@@ -9,15 +9,16 @@     ) where -import Atelier.Effects.FileSystem (FileSystem) import Atelier.Effects.Input (Input)+import Atelier.FileSystem.Path ((</>)) import Data.Aeson (FromJSON)+import Effectful.FileSystem (FileSystem) import Effectful.Reader.Static (Reader) import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)-import System.FilePath ((</>)) -import Atelier.Effects.FileSystem qualified as FileSystem import Atelier.Effects.Input qualified as Input+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path import Data.Aeson qualified as Aeson import Data.Aeson.KeyMap qualified as KM import Data.List qualified as List@@ -25,7 +26,7 @@ import Data.Yaml qualified as Yaml import Effectful.Reader.Static qualified as Reader -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..))   newtype LoadedConfig = LoadedConfig {getLoadedConfig :: ByteString}@@ -37,10 +38,10 @@ asInput = Input.withEff do     ProjectRoot projectRoot <- Reader.ask     let configFilePath = projectRoot </> configFileName-    exists <- FileSystem.doesFileExist configFilePath+    exists <- File.exists configFilePath     if exists         then do-            bs <- FileSystem.readFileBs configFilePath+            bs <- File.read configFilePath             pure $ LoadedConfig bs         else pure $ LoadedConfig "" @@ -57,8 +58,8 @@     pure $ decodeNestedValue @key loadedConfig  -configFileName :: FilePath-configFileName = ".tricorder.yaml"+configFileName :: Path.Relative+configFileName = Path.relative @".tricorder.yaml"   decodeNestedValue
src/Tricorder/Daemon/Builder.hs view
@@ -21,18 +21,19 @@ import Effectful.Reader.Static (Reader, ask) import Effectful.State.Static.Shared (State, get, modify) import Effectful.TH (makeEffect)-import System.FilePath (normalise)  import Atelier.Effects.Clock qualified as Clock import Atelier.Effects.FileWatcher.Event qualified as FileWatcher (Event) import Atelier.Effects.Log qualified as Log import Atelier.Effects.PubSub.Pub qualified as Pub+import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map import Data.Set qualified as Set import Effectful.State.Static.Shared qualified as State -import Tricorder.Build (BuildId (..), BuildProgress, BuildResult (..), Diagnostic (..))+import Tricorder.Build.Diagnostic (Diagnostic (..)) import Tricorder.Build.Duration (Duration (..))+import Tricorder.Build.Id (Id (..)) import Tricorder.Daemon.Dispatch     ( BuilderState (..)     , DiagnosticMap@@ -44,10 +45,13 @@     , mergeDiagnostics     , preserveFailureVisibility     )-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.Command.RenderedCommand (RenderedCommand) import Tricorder.Session.WatchDirs (WatchDirs) +import Tricorder.Build.Id qualified as Build (Id)+import Tricorder.Build.Progress qualified as Build (Progress)+import Tricorder.Build.Result qualified as Build (Result (..)) import Tricorder.Daemon.Ghci.Controls qualified as Controls import Tricorder.Daemon.Ghci.Controls qualified as Ghci (Controls) import Tricorder.Daemon.Ghci.LoadResult qualified as Ghci (LoadResult)@@ -58,7 +62,7 @@   data Builder :: Effect where-    Consider :: FilePath -> FileWatcher.Event -> Builder m BuildConsideration+    Consider :: Path.Any -> FileWatcher.Event -> Builder m BuildConsideration     Build :: DispatchAction -> Builder m (Either BuildFailure NewLoadResult)  @@ -87,10 +91,10 @@     :: ( Clock :> es        , Ghci.Session :> es        , Log :> es-       , Pub BuildProgress :> es+       , Pub Build.Progress :> es        , Reader ProjectRoot :> es        )-    => BuildId+    => Build.Id     -> RenderedCommand 'Stage.Build     -> WatchDirs     -> (BuilderState -> NewLoadResult -> Eff (Builder : es) a)@@ -104,7 +108,7 @@         Log.info             $ mconcat                 [ "GHCi started (session #"-                , show buildId.getBuildId+                , show buildId.getId                 , "): "                 , show (length filteredMsgs)                 , " diagnostics"@@ -126,12 +130,12 @@  considerBuild     :: (State BuilderState :> es)-    => FilePath+    => Path.Any     -> FileWatcher.Event     -> Eff es BuildConsideration considerBuild fp event = do     builderState <- get-    let known = Map.lookup (normalise fp) builderState.loadedModules+    let known = Map.lookup (Path.normalise fp) builderState.loadedModules     case dispatch builderState.knownTargets known fp event of         Nothing ->             -- File not loaded in GHCi, so we skip building.@@ -169,7 +173,7 @@     -> WatchDirs     -> DiagnosticMap     -> NewLoadResult-    -> (DiagnosticMap, BuildResult)+    -> (DiagnosticMap, Build.Result) compileBuildResults (ProjectRoot projectRoot) watchDirs diagnosticMap newLoadResult =     (merged, buildResult)   where@@ -182,7 +186,7 @@                     $ filterToWatchDirs projectRoot watchDirs loadResult.diagnostics             }     buildResult =-        BuildResult+        Build.Result             { completedAt = endTime             , duration = Duration $ nominalDiffTime (diffUTCTime endTime startTime)             , moduleCount = loadResult.moduleCount
src/Tricorder/Daemon/Core.hs view
@@ -7,24 +7,35 @@ import Atelier.Effects.Process (Process) import Atelier.Effects.PubSub.Pub (Pub) import Atelier.Effects.PubSub.Sub (Sub)-import Effectful.Concurrent.MVar (newEmptyMVar, takeMVar, tryPutMVar)-import Effectful.Concurrent.STM (Concurrent, atomically, newEmptyTMVar, takeTMVar, writeTMVar)+import Effectful.Concurrent.STM+    ( Concurrent+    , STM+    , TVar+    , atomically+    , modifyTVar'+    , newTVarIO+    , readTVar+    , retry+    ) import Effectful.Reader.Static (Reader) import Effectful.State.Static.Shared (State) import Relude.Extra.Tuple (dup)  import Atelier.Effects.Conc qualified as Conc+import Atelier.Effects.FileWatcher.Event qualified as Event import Atelier.Effects.FileWatcher.Event qualified as FileWatcher (Event) import Atelier.Effects.Log qualified as Log import Atelier.Effects.PubSub qualified as PubSub import Atelier.Effects.PubSub.Pub qualified as Pub import Atelier.Effects.PubSub.Sub qualified as Sub+import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map import Effectful.Reader.Static qualified as Reader import Effectful.State.Static.Shared qualified as State -import Tricorder.Build (BuildId, BuildPhase, BuildResult, PostBuild (..), Severity (..))-import Tricorder.Build.Changes (CabalChangeDetected (..), SourceChangeDetected (..))+import Tricorder.Build.Changes (ProjectChangeDetected (..), SourceChangeDetected (..))+import Tricorder.Build.Diagnostic (Diagnostic (..))+import Tricorder.Build.PostBuild (PostBuild (..)) import Tricorder.Daemon.Builder     ( BuildConsideration (..)     , BuildFailure@@ -32,17 +43,21 @@     , NewLoadResult     , compileBuildResults     )-import Tricorder.Daemon.Dispatch (BuilderState (..), DispatchAction, emptyBuilderState)+import Tricorder.Daemon.Dispatch (BuilderState (..), emptyBuilderState, planActions) import Tricorder.Daemon.EvalCommentRunner (EvalCommentRunner, findEvalCommentsInModules) import Tricorder.Daemon.Ghci.LoadedModule (LoadedModule (..)) import Tricorder.Daemon.TestRunner (TestRunner)-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot) import Tricorder.Session (Session (..)) import Tricorder.Session.Stage.Test.Command (RenderedTestCommand (..)) import Tricorder.Waiters (Waiters) -import Tricorder.Build qualified as Build import Tricorder.Build.EvalComment qualified as Eval+import Tricorder.Build.Id qualified as Build (Id (..))+import Tricorder.Build.Phase qualified as Build (Phase)+import Tricorder.Build.Phase qualified as Phase+import Tricorder.Build.Result qualified as Build (Result (..))+import Tricorder.Build.Severity qualified as Severity import Tricorder.Build.Test qualified as Test import Tricorder.Daemon.Builder qualified as Builder import Tricorder.Daemon.EvalCommentRunner qualified as EvalCommentRunner@@ -64,7 +79,7 @@ data RestartBuilder = RestartBuilder  -data ReloadBuilder = ReloadBuilder FilePath FileWatcher.Event+data ReloadBuilder = ReloadBuilder Path.Any FileWatcher.Event   -- | Top of the build loop. Responsible for handling changes to the Tricorder@@ -78,10 +93,10 @@        , Ghci.Session :> es        , Log :> es        , Process :> es-       , Pub BuildPhase :> es+       , Pub Build.Phase :> es        , Reader ProjectRoot :> es-       , State BuildId :> es-       , Sub CabalChangeDetected :> es+       , State Build.Id :> es+       , Sub ProjectChangeDetected :> es        , Sub SourceChangeDetected :> es        , TestRunner :> es        , Waiters :> es@@ -93,7 +108,7 @@         $ Conc.restartableFork (Waiters.wait $ Sub.listenOnce_ @RestartBuilder) do             buildId <- State.state (\s -> (s, s + 1)) -            Conc.fork_ $ Sub.listen_ \(CabalChangeDetected _ _) ->+            Conc.fork_ $ Sub.listen_ \(ProjectChangeDetected _ _) ->                 Pub.publish RestartBuilder              Conc.fork_ $ Sub.listen_ \(SourceChangeDetected path event) ->@@ -111,39 +126,43 @@        , Ghci.Session :> es        , Log.Log :> es        , Process :> es-       , Pub BuildPhase :> es+       , Pub Build.Phase :> es        , Reader ProjectRoot :> es        , Sub ReloadBuilder :> es        , TestRunner :> es        , Waiters :> es        )-    => BuildId -> Session -> Eff es ()+    => Build.Id -> Session -> Eff es () runBuilder buildId session = State.evalState emptyBuilderState do-    Log.info $ "Starting session " <> show buildId.getBuildId-    Pub.publish Build.Starting+    Log.info $ "Starting session " <> show buildId.getId+    Pub.publish Phase.Starting     whenJust (session.hooks.start >>= (.before)) Hook.run     startupError <- fmap (either id absurd)-        $ Pub.map (Build.Building $ Test.Session.targets session.testSession)+        $ Pub.map (Phase.Building $ Test.Session.targets session.testSession)         $ Builder.with buildId buildCommand session.watchDirs \_ initialLoad -> do             whenJust (session.hooks.start >>= (.after)) Hook.run             processPostBuild session $ Right initialLoad             Log.debug "Waiting for reload"-            newestReloadEvent <- atomically newEmptyTMVar-            cancelSem <- newEmptyMVar-            let requestCancel = tryPutMVar cancelSem ()-                checkCancel = takeMVar cancelSem+            pending <- newTVarIO emptyPending             Conc.fork_ $ Sub.listen_ @ReloadBuilder \event -> do-                atomically $ writeTMVar newestReloadEvent event-                Waiters.without do-                    Pub.publish Build.Starting-                    Log.debug "Cancelling current build"-                    requestCancel+                Log.debug "Got request to reload builder"+                atomically $ modifyTVar' pending (addPending event)++            -- Events stay pending until a build that covered them has finished,+            -- so a build cancelled by a newer event is redone with both.             forever do-                event <- atomically $ takeTMVar newestReloadEvent-                Conc.restartableFork checkCancel-                    $ waitForReload session event+                batch <- atomically $ takeBatch pending+                Conc.scoped do+                    _ <- Conc.fork do+                        processBatch session $ snd <$> batch.items+                        atomically $ modifyTVar' pending (dropCovered batch)+                    -- Return (cancelling the build, if it is still running) as+                    -- soon as an event newer than the batch shows up. If a+                    -- build is currently running, it will be restarted, not+                    -- dropped.+                    atomically $ waitForNewerThan batch pending -    Pub.publish $ Build.Failed $ toText $ displayException startupError+    Pub.publish $ Phase.Failed $ toText $ displayException startupError   where     buildCommand =         Build.Command.render@@ -151,61 +170,64 @@             session.buildSession.targets  --- | Handles source changes as they come, determining whether the source change--- detected warrants a rebuild.-waitForReload+-- | Handles a batch of source changes, determining which of them warrant a+-- rebuild, and what GHCi needs to do about them.+processBatch     :: ( Builder :> es        , Conc :> es        , EvalCommentRunner :> es        , Log :> es        , Process :> es-       , Pub BuildPhase :> es+       , Pub Build.Phase :> es        , Reader ProjectRoot :> es        , State BuilderState :> es        , TestRunner :> es+       , Waiters :> es        )-    => Session -> ReloadBuilder -> Eff es ()-waitForReload session (ReloadBuilder fp event) = do-    Log.debug $ "Considering " <> toText fp-    consideration <- Builder.consider fp event-    case consideration of-        SkipBuilding -> do-            Log.debug $ "Skipping " <> toText fp-            pure ()-        ShouldBuild action -> do-            Log.debug $ "Should build " <> toText fp-            processSource session action-    Log.info "Reload finished"+    => Session -> [ReloadBuilder] -> Eff es ()+processBatch session events = do+    considered <- forM (Event.collapse [(fp, event) | ReloadBuilder fp event <- events]) \(fp, event) -> do+        Log.debug $ "Considering " <> toText fp+        consideration <- Builder.consider fp event+        case consideration of+            SkipBuilding -> do+                Log.debug $ "Skipping " <> toText fp+                pure Nothing+            ShouldBuild action -> do+                Log.debug $ "Should build " <> toText fp+                pure $ Just action+    case nonEmpty $ planActions $ catMaybes considered of+        Nothing -> Log.debug "Nothing to build"+        Just actions -> do+            -- Only flip the phase once we know a build will follow.+            Waiters.without $ Pub.publish Phase.Starting+            whenJust (session.hooks.reload >>= (.before)) Hook.run+            let fullAction = last actions+                intermediateActions = init actions +            -- Process intermediate changes in GHCi first. Usually there is a+            -- single action, so there are no intermediate actions to run. Only+            -- drive GHCi (and fold their diagnostics into the state) for the+            -- intermediate changes.+            for_ intermediateActions \action -> do+                res <- Builder.build action+                Log.debug $ "Finished intermediate build: " <> show action+                for_ (rightToMaybe res) \newLoadResult ->+                    void $ newLoadResultToBuildResult session newLoadResult --- | Rebuilds the project on source change.-processSource-    :: ( Builder :> es-       , Conc :> es-       , EvalCommentRunner :> es-       , Log :> es-       , Process :> es-       , Pub BuildPhase :> es-       , Reader ProjectRoot :> es-       , State BuilderState :> es-       , TestRunner :> es-       )-    => Session-    -> DispatchAction-    -> Eff es ()-processSource session action = do-    whenJust (session.hooks.reload >>= (.before)) Hook.run-    res <- Builder.build action-    whenJust (session.hooks.reload >>= (.after)) Hook.run-    Log.debug "Finished build"-    processPostBuild session res+            -- Fully process the last change.+            result <- Builder.build fullAction+            Log.debug $ "Finished build: " <> show fullAction+            whenJust (session.hooks.reload >>= (.after)) Hook.run+            processPostBuild session result+    Log.info "Reload finished"   processPostBuild     :: ( Conc :> es        , EvalCommentRunner :> es        , Log :> es-       , Pub BuildPhase :> es+       , Pub Build.Phase :> es        , Reader ProjectRoot :> es        , State BuilderState :> es        , TestRunner :> es@@ -214,12 +236,12 @@ processPostBuild session = \case     Left buildFailure -> do         Log.debug "Build failure"-        Pub.publish $ Build.Failed $ show buildFailure+        Pub.publish $ Phase.Failed $ show buildFailure     Right newLoadResult -> do         Log.debug "Built"         buildResult <- newLoadResultToBuildResult session newLoadResult         let initialPostBuild = PostBuild mempty Eval.Looking-        Pub.publish $ Build.PostBuilding buildResult initialPostBuild+        Pub.publish $ Phase.PostBuilding buildResult initialPostBuild         State.evalState initialPostBuild $ Conc.scoped do             evalCommentsP <-                 Conc.fork@@ -233,14 +255,14 @@             Log.debug "Eval comments finished"             tests <- Conc.await testsP             Log.debug "Tests finished"-            Pub.publish $ Build.Finished buildResult $ PostBuild tests evalComments+            Pub.publish $ Phase.Finished buildResult $ PostBuild tests evalComments   where     updateEvalComments buildResult evalComments = do         newPostBuild <- State.state \postBuild -> dup $ postBuild {evalComments}-        Pub.publish $ Build.PostBuilding buildResult newPostBuild+        Pub.publish $ Phase.PostBuilding buildResult newPostBuild     updateTestSuites buildResult testSuites = do         newPostBuild <- State.state \postBuild -> dup $ postBuild {testSuites}-        Pub.publish $ Build.PostBuilding buildResult newPostBuild+        Pub.publish $ Phase.PostBuilding buildResult newPostBuild   runEvalComments@@ -277,14 +299,14 @@        , Pub Test.Suites :> es        , TestRunner :> es        )-    => Session -> BuildResult -> Eff es Test.Suites+    => Session -> Build.Result -> Eff es Test.Suites runTests session buildResult     | hasTargets session.testSession.targets && noErrors buildResult.diagnostics =         runTestsForTargets session.testSession     | otherwise = pure mempty   where     hasTargets = not . null-    noErrors = all \d -> d.severity /= SError+    noErrors = all \d -> d.severity /= Severity.Error   runTestsForTargets@@ -325,7 +347,7 @@  newLoadResultToBuildResult     :: (Reader ProjectRoot :> es, State BuilderState :> es)-    => Session -> NewLoadResult -> Eff es BuildResult+    => Session -> NewLoadResult -> Eff es Build.Result newLoadResultToBuildResult session newLoadResult = do     root <- Reader.ask     State.state \s ->@@ -336,3 +358,61 @@                     s.diagnosticMap                     newLoadResult         in  (buildResult, s {diagnosticMap = newDiagnosticMap})+++-- | Source events waiting for a build to cover them. Each gets an increasing+-- id so a batch can tell which events are newer than it.+data Pending = Pending+    { nextId :: Int+    , events :: [(Int, ReloadBuilder)]+    }+++-- | A snapshot of the pending events, taken when a build starts.+data Batch = Batch+    { newestId :: Int+    , items :: [(Int, ReloadBuilder)]+    }+++emptyPending :: Pending+emptyPending =+    Pending+        { nextId = 0+        , events = []+        }+++addPending :: ReloadBuilder -> Pending -> Pending+addPending event p =+    Pending+        { nextId = p.nextId + 1+        , events = p.events <> [(p.nextId, event)]+        }+++-- | Blocks until there is something pending, then snapshots it.+takeBatch :: TVar Pending -> STM Batch+takeBatch pending = do+    p <- readTVar pending+    when (null p.events) retry+    pure+        Batch+            { newestId = foldl' (\m -> max m . fst) 0 p.events+            , items = p.events+            }+++-- | Blocks until an event newer than the batch is pending.+waitForNewerThan :: Batch -> TVar Pending -> STM ()+waitForNewerThan batch pending = do+    p <- readTVar pending+    unless (any ((> batch.newestId) . fst) p.events) retry+++-- | Forgets the events a finished build covered, keeping any newer ones.+dropCovered :: Batch -> Pending -> Pending+dropCovered batch p =+    p+        { events = filter ((> batch.newestId) . fst) p.events+        }
src/Tricorder/Daemon/DaemonInfo.hs view
@@ -1,34 +1,33 @@ module Tricorder.Daemon.DaemonInfo     ( DaemonInfo (..)     , load-    , runInput+    , asInput     ) where  import Atelier.Effects.Input (Input)-import Data.Aeson (FromJSON (..), ToJSON (..))+import Atelier.Types.JSON.QuietSnake+    ( QuietSnake (..)+    )+import Data.Aeson (ToJSON) import Effectful.Reader.Static (Reader, ask)-import GHC.Generics (Generically (..))-import System.FilePath (makeRelative)  import Atelier.Effects.Input qualified as Input -import Tricorder.Runtime (LogPath (..), ProjectRoot (..), SocketPath (..))+import Tricorder.Runtime.LogPath (LogPath (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..))+import Tricorder.Runtime.SocketPath (SocketPath (..)) import Tricorder.Session (Session (..))-import Tricorder.Session.Target (Target)-import Tricorder.Session.WatchDirs (WatchDirs (..)) -import Tricorder.Session.Stage.Build.Session qualified as Build.Session - data DaemonInfo = DaemonInfo-    { targets :: [Target]-    , watchDirs :: [FilePath]-    , sockPath :: FilePath-    , logFile :: FilePath+    { session :: Session+    , sockPath :: SocketPath+    , logFile :: LogPath+    , projectRoot :: ProjectRoot     }-    deriving stock (Eq, Generic, Show)-    deriving (FromJSON, ToJSON) via Generically DaemonInfo+    deriving stock (Eq, Generic)+    deriving (ToJSON) via QuietSnake DaemonInfo   load@@ -40,23 +39,23 @@     => Eff es DaemonInfo load = do     session <- Input.input-    ProjectRoot projectRoot <- ask-    SocketPath sockPath <- ask-    LogPath logFile <- ask+    projectRoot <- ask+    sockPath <- ask+    logFile <- ask     pure         $ DaemonInfo-            { targets = Build.Session.targets session.buildSession-            , watchDirs = map (makeRelative projectRoot) session.watchDirs.getWatchDirs+            { session             , sockPath             , logFile+            , projectRoot             }  -runInput+asInput     :: ( Input Session :> es        , Reader LogPath :> es        , Reader ProjectRoot :> es        , Reader SocketPath :> es        )     => Eff (Input DaemonInfo : es) a -> Eff es a-runInput = Input.withEff load+asInput = Input.withEff load
src/Tricorder/Daemon/Dispatch.hs view
@@ -9,20 +9,25 @@     , filterToWatchDirs     , mergeDiagnostics     , preserveFailureVisibility+    , planActions     ) where -import System.FilePath (isAbsolute, normalise, splitDirectories, takeExtension, (</>))+import Atelier.FileSystem.Path (Path, (</>))  import Atelier.Effects.FileWatcher.Event qualified as FileWatcher (Event) import Atelier.Effects.FileWatcher.Event qualified as FileWatcher.Event+import Atelier.FileSystem.Path qualified as Path import Data.List qualified as List import Data.Map.Strict qualified as Map import Data.Set qualified as Set+import System.FilePath qualified as FP -import Tricorder.Build (Diagnostic (..), Severity (..))+import Tricorder.Build.Diagnostic (Diagnostic (..))+import Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..)) import Tricorder.Session.WatchDirs (WatchDirs (..)) +import Tricorder.Build.Severity qualified as Severity import Tricorder.Daemon.Ghci.Diagnostic qualified as Ghci.Diagnostic import Tricorder.Daemon.Ghci.LoadResult qualified as Ghci import Tricorder.Daemon.Ghci.LoadedModule qualified as Ghci (LoadedModule)@@ -35,7 +40,7 @@ -- @buildWithGhciOnChange@; 'BuildId' is intentionally /not/ here because it -- counts across restarts. data BuilderState = BuilderState-    { loadedModules :: Map FilePath Ghci.LoadedModule+    { loadedModules :: Map Path.Any Ghci.LoadedModule     , knownTargets :: KnownTargetNames     , diagnosticMap :: DiagnosticMap     }@@ -51,7 +56,7 @@         }  -type DiagnosticMap = Map FilePath [Diagnostic]+type DiagnosticMap = Map DiagnosticLocation [Diagnostic]   -- | Merge a new 'LoadResult' into the accumulated per-file diagnostic map.@@ -59,17 +64,31 @@ -- Files in 'compiledFiles' have their previous diagnostics cleared and replaced -- by any new diagnostics produced for them in this cycle. Files absent from -- 'compiledFiles' were skipped by incremental compilation and retain their--- previous diagnostics unchanged.+-- previous /warnings/ (GHC never re-emits those for unchanged modules). ----- Location-less diagnostics (see 'isLocationLess') are never keyed to a real--- source file, so they would never appear in 'compiledFiles' and would persist+-- Errors are never retained: GHC retries every failed module on each reload,+-- so a still-present error is always re-emitted. The exception is a module+-- blocked behind a failing upstream module, which GHC does not recompile.+-- Retaining its old errors would leave them stale (e.g. an import error that+-- has since been fixed) until the upstream failure is resolved. The upstream+-- error keeps the build failing, and the blocked module's errors reappear once+-- it is compiled again.+--+-- 'Locationless' diagnostics are never keyed to a real source file, so they+-- would never appear in 'compiledFiles' and would persist -- forever once raised. They describe the current load's outcome, so we clear -- them every cycle and let this cycle's 'diagnostics' re-add them if the -- failure is still present. mergeDiagnostics :: DiagnosticMap -> Ghci.LoadResult -> DiagnosticMap mergeDiagnostics prev Ghci.LoadResult {compiledFiles, diagnostics} =-    let retained = Map.filterWithKey (\f _ -> not (Ghci.Path.isLocationLess f)) prev-        cleared = foldr Map.delete retained compiledFiles+    let retained =+            Map.mapMaybeWithKey+                ( \f ds -> case filter ((== Severity.Warning) . (.severity)) ds of+                    ws | f /= Locationless, not (null ws) -> Just ws+                    _ -> Nothing+                )+                prev+        cleared = foldr (Map.delete . Location) retained compiledFiles         newByFile = Map.fromListWith (++) [(d.file, [d]) | d <- diagnostics]     in  Map.union newByFile cleared @@ -93,7 +112,7 @@ -- @:show modules@ but survives in @:show targets@ as its path. Without matching -- it, fixing the executable would dispatch a no-op 'Add' instead of a 'Reload', -- leaving the diagnostic stale.-fileMatchesAnyTarget :: KnownTargetNames -> FilePath -> Bool+fileMatchesAnyTarget :: (Path path) => KnownTargetNames -> path -> Bool fileMatchesAnyTarget (KnownTargetNames targets) fp =     any (`Set.member` targets) (Ghci.Path.pathSuffixesAsModuleName fp)         || any (pathTargetMatches fp . toString) (Set.toList targets)@@ -101,18 +120,21 @@  -- | Whether a path-shaped @:show targets@ entry refers to the given file, -- compared on directory-segment boundaries (so @app/Main.hs@ matches--- @./tricorder/app/Main.hs@ but @pp/Main.hs@ does not). Module-name targets+-- @.\/tricorder\/app/Main.hs@ but @pp/Main.hs@ does not). Module-name targets -- (no @.hs@ extension) are left to the module-name branch above.-pathTargetMatches :: FilePath -> FilePath -> Bool+pathTargetMatches :: (Path path) => path -> FilePath -> Bool pathTargetMatches file target =-    takeExtension target == ".hs"-        && splitDirectories (normalise target) `List.isSuffixOf` splitDirectories (normalise file)+    FP.takeExtension target == ".hs"+        && (FP.splitDirectories $ FP.normalise target)+            `List.isSuffixOf` merge (Path.splitDirectories $ Path.normalise file)+  where+    merge (a, rest) = Path.toFilePath a : (Path.toFilePath <$> rest)   -- | A GHCi command to issue in response to a source file change. data DispatchAction     = Reload-    | Add FilePath+    | Add Path.Any     | Unadd Text     deriving stock (Eq, Show) @@ -126,19 +148,22 @@ dispatch     :: KnownTargetNames     -> Maybe Ghci.LoadedModule-    -> FilePath+    -> Path.Any     -> FileWatcher.Event     -> Maybe DispatchAction dispatch knownTargets known fp event = case known of     Just lm -> Just $ case event of         FileWatcher.Event.Added -> Reload         FileWatcher.Event.Modified -> Reload-        FileWatcher.Event.Removed -> Unadd lm.moduleName+        FileWatcher.Event.Removed -> Unadd $ lm.moduleName <> " " <> toText fp     Nothing         | fileMatchesAnyTarget knownTargets fp -> case event of             FileWatcher.Event.Added -> Just Reload             FileWatcher.Event.Modified -> Just Reload-            FileWatcher.Event.Removed -> Nothing+            -- A target that failed to compile is absent from the module map,+            -- but still registered with GHCi, so it must be unadded too.+            -- Otherwise, every later laod fails on the missing file.+            FileWatcher.Event.Removed -> Just $ Unadd $ toText fp         | otherwise -> case event of             FileWatcher.Event.Added -> Just (Add fp)             FileWatcher.Event.Modified -> Just (Add fp)@@ -152,35 +177,26 @@ -- @"In file included from ..."@) are dropped here, before they can enter the -- accumulation map where they would be impossible to evict. ----- Location-less diagnostics (see 'isLocationLess') are always kept: they carry--- no path to test against a watch dir, but they represent genuine build-level--- failures (e.g. a home-unit GHC plugin that can't load under--- @--enable-multi-repl@) that must not be dropped, or the build would silently--- read as clean.-filterToWatchDirs :: FilePath -> WatchDirs -> [Diagnostic] -> [Diagnostic]+-- Location-less diagnostics are always kept: they carry no path to test+-- against a watch dir, but they represent genuine build-level failures (e.g. a+-- home-unit GHC plugin that can't load under @--enable-multi-repl@) that must+-- not be dropped, or the build would silently read as clean.+filterToWatchDirs :: Path.Absolute -> WatchDirs -> [Diagnostic] -> [Diagnostic] filterToWatchDirs _ (WatchDirs []) diags = diags filterToWatchDirs projectRoot (WatchDirs watchDirs) diags =-    filter (\d -> Ghci.Path.isLocationLess d.file || isUnderAnyWatchDir d.file) diags+    filter+        ( \d -> case d.file of+            Locationless -> True+            Location file -> isUnderAnyWatchDir file+        )+        diags   where-    absWatchDirs = map toAbsWd watchDirs-    toAbsWd wd-        | wd == "." = projectRoot-        | isAbsolute wd = wd-        | otherwise = projectRoot </> wd-    isUnderAnyWatchDir file-        | isCPPMangledFile file = False-        | isAbsolute file =-            any (\wd -> (wd ++ "/") `isPrefixOf` file || wd == file) absWatchDirs-        | otherwise =-            let absFile = projectRoot </> normalizeRelativePath file-            in  any (\wd -> (wd ++ "/") `isPrefixOf` absFile || wd == absFile) absWatchDirs-    isCPPMangledFile = ("In file included from" `isPrefixOf`)-    normalizeRelativePath file-        -- GHCi reports filenames relative to the project root for-        -- single-package repos. E.g. "src/Foo/Bar.hs", instead of-        -- an absolute path or a "./" prefixed path.-        | "./" `isPrefixOf` file = drop 2 file-        | otherwise = file+    isUnderAnyWatchDir = \case+        file | isCPPMangledFile file -> False+        Path.Absolute file -> isInWatchDirs file+        Path.Relative file -> isInWatchDirs $ projectRoot </> Path.normalise file+    isInWatchDirs file = any (\wd -> wd `Path.isPrefixOf` file || wd == file) watchDirs+    isCPPMangledFile = ("In file included from" `isPrefixOf`) . Path.toFilePath   -- | Keep a failed build from ever reading as clean after watch-dir filtering.@@ -200,4 +216,18 @@     | any isError raw && not (any isError filtered) = filtered ++ [Ghci.Diagnostic.unattributedFailure]     | otherwise = filtered   where-    isError d = d.severity == SError+    isError d = d.severity == Severity.Error+++-- | Reduce the actions a batch of events asked for to those that need to run.+--+-- @:add@ and @:unadd@ both go on to load every target, so they subsume a plain+-- @:reload@: any 'Reload' is dropped when a target change is present.+-- Duplicates are dropped, and order is kept otherwise.+planActions :: [DispatchAction] -> [DispatchAction]+planActions actions =+    case filter (/= Reload) deduped of+        [] -> take 1 deduped+        targetChanges -> targetChanges+  where+    deduped = List.nub actions
src/Tricorder/Daemon/EvalCommentRunner.hs view
@@ -10,8 +10,7 @@ where  import Atelier.Effects.Conc (Conc)-import Atelier.Effects.File (File)-import Atelier.Effects.FileSystem (FileSystem, readFileBs)+import Atelier.Effects.Handles (Handles) import Atelier.Effects.Log (Log) import Atelier.Effects.Process (Process) import Atelier.Effects.Timeout (Timeout)@@ -21,15 +20,18 @@ import Effectful.Concurrent (Concurrent) import Effectful.Dispatch.Dynamic (interpretWith_) import Effectful.Exception (trySync)+import Effectful.FileSystem (FileSystem) import Effectful.Reader.Static (Reader, ask) import Effectful.TH (makeEffect)  import Atelier.Effects.Log qualified as Log+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map import Data.Text qualified as T  import Tricorder.Daemon.Ghci.LoadedModule (LoadedModule (..))-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.Stage.Eval.Session (Session (..))  import Tricorder.Build.EvalComment qualified as Eval@@ -49,7 +51,7 @@     -- | Extract eval comments from provided source files. Returns a map of all     -- files that have at least 1 eval comment.     FindEvalCommentsInModules-        :: Map FilePath Ghci.LoadedModule+        :: Map Path.Any Ghci.LoadedModule         -> EvalCommentRunner m [(Ghci.LoadedModule, NonEmpty Eval.Comment)]  @@ -62,8 +64,8 @@ run     :: ( Conc :> es        , Concurrent :> es-       , File :> es        , FileSystem :> es+       , Handles :> es        , Log :> es        , Process :> es        , Reader ProjectRoot :> es@@ -74,7 +76,7 @@     interpretWith_ act \case         FindEvalCommentsInModules loadedModules -> do             concat <$> for (Map.toList loadedModules) \(absPath, lm) -> do-                fileResult <- trySync $ readFileBs absPath+                fileResult <- trySync $ File.read absPath                 pure $ case fileResult of                     Left _ -> []                     Right bs ->@@ -99,14 +101,14 @@ runFileEvals     :: ( Conc :> es        , Concurrent :> es-       , File :> es+       , Handles :> es        , Log :> es        , Process :> es        , Reader ProjectRoot :> es        , Timeout :> es        )     => Session-    -> FilePath+    -> Path.Relative     -- ^ Relative path to the source file (stored in results).     -> Text     -> NonEmpty Eval.Comment
src/Tricorder/Daemon/Ghci/Config.hs view
@@ -4,7 +4,9 @@     ) where -import Atelier.Time (Second)+import Atelier.Time (AsRawUnit (..), Second)+import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (ToJSON) import Data.Default (Default (..))  import Data.Text qualified as T@@ -14,22 +16,23 @@  -- | Configuration for GHCi process management. data Config = Config-    { startupTimeout :: Second+    { startupTimeout :: AsRawUnit Second     -- ^ How long to wait for the GHCi version banner on startup.-    , shutdownTimeout :: Second+    , shutdownTimeout :: AsRawUnit Second     -- ^ How long to wait for the process to exit gracefully before force-killing.     , extraSetupCommands :: [Text]     -- ^ Additional GHCi commands to send after the fixed setup block.     -- Use this to inject session-wide options such as @:set -XOverloadedStrings@.     }-    deriving stock (Eq)+    deriving stock (Eq, Generic)+    deriving (ToJSON) via QuietSnake Config   instance Default Config where     def =         Config-            { startupTimeout = 60-            , shutdownTimeout = 5+            { startupTimeout = AsRawUnit 60+            , shutdownTimeout = AsRawUnit 5             , extraSetupCommands = []             } 
src/Tricorder/Daemon/Ghci/Config/File.hs view
@@ -36,8 +36,8 @@ toConfig :: File -> Config toConfig file =     Config-        { startupTimeout = maybe cfg.startupTimeout (Time.convertUnit . getAsRawUnit) file.startupTimeoutMs-        , shutdownTimeout = maybe cfg.shutdownTimeout (Time.convertUnit . getAsRawUnit) file.shutdownTimeoutMs+        { startupTimeout = maybe cfg.startupTimeout (fmap Time.convertUnit) file.startupTimeoutMs+        , shutdownTimeout = maybe cfg.shutdownTimeout (fmap Time.convertUnit) file.shutdownTimeoutMs         , extraSetupCommands = fromMaybe cfg.extraSetupCommands file.extraSetupCommands         }   where
src/Tricorder/Daemon/Ghci/Controls.hs view
@@ -4,13 +4,15 @@     ) where +import Atelier.FileSystem.Path qualified as Path+ import Tricorder.Daemon.Ghci.LoadResult (LoadResult)   data Controls m = Controls     { reload :: m LoadResult     , interrupt :: m ()-    , add :: FilePath -> m LoadResult+    , add :: Path.Any -> m LoadResult     , unadd :: Text -> m LoadResult     } 
src/Tricorder/Daemon/Ghci/Diagnostic.hs view
@@ -9,12 +9,15 @@ import Text.Megaparsec.Char (char) import Prelude hiding (many) +import Atelier.FileSystem.Path qualified as Path import Data.Text qualified as T -import Tricorder.Build (Diagnostic (..), Severity (..))+import Tricorder.Build.Diagnostic (Diagnostic (..))+import Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..)) import Tricorder.Daemon.Ghci.Position (Position) import Tricorder.Daemon.Ghci.TextParser (TextParser) +import Tricorder.Build.Severity qualified as Severity import Tricorder.Daemon.Ghci.Position qualified as Position  @@ -24,8 +27,8 @@ unattributedFailure :: Diagnostic unattributedFailure =     Diagnostic-        { severity = SError-        , file = "<no location info>"+        { severity = Severity.Error+        , file = Locationless         , line = 0         , col = 0         , endLine = 0@@ -39,7 +42,7 @@ -- | Parse the full diagnostic header: --   @file:pos:@ or @drive:path:pos:@ for Windows. -- Returns @(file, startPos, endPos, textAfterColon)@.-headerParser :: TextParser (Text, Position, Position, Text)+headerParser :: TextParser (Path.Any, Position, Position, Text) headerParser = do     a <- takeWhile1P Nothing (/= ':')     _ <- char ':'@@ -51,6 +54,9 @@                 pure (a <> ":" <> pathRest)             else                 pure a-    (sp, ep) <- Position.parser-    afterPos <- getInput-    pure (filePart, sp, ep, afterPos)+    case Path.fromFilePath @Path.Any $ toString filePart of+        Left _ -> fail $ "not a valid file path: " <> toString filePart+        Right path -> do+            (sp, ep) <- Position.parser+            afterPos <- getInput+            pure (path, sp, ep, afterPos)
src/Tricorder/Daemon/Ghci/Load.hs view
@@ -8,10 +8,12 @@ import Text.Megaparsec (anySingle, choice, satisfy, takeWhile1P, takeWhileP) import Text.Megaparsec.Char (char, string) +import Atelier.FileSystem.Path qualified as Path import Data.Char qualified as Char import Data.Text qualified as T import Text.Megaparsec.Char.Lexer qualified as L +import Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..)) import Tricorder.Daemon.Ghci.LineParser (LineParser) import Tricorder.Daemon.Ghci.LoadOutcome (LoadOutcome) import Tricorder.Daemon.Ghci.Position (Position (..))@@ -66,7 +68,7 @@                 $ Message                     Ghci.Message                         { severity = Severity.Error-                        , file = "<no location info>"+                        , file = Locationless                         , startPos = Position 0 0                         , endPos = Position 0 0                         , messageLines = origLine : body@@ -82,20 +84,20 @@                     )             case TextParser.run Diagnostic.headerParser stripped of                 Nothing -> pure Nothing-                Just (fileT, sp, ep, afterPos) ->+                Just (file, startPos, endPos, afterPos) ->                     let lower = T.toLower (T.stripStart afterPos)                     in  case Severity.parse lower of                             Nothing -> pure Nothing-                            Just sev -> do+                            Just severity -> do                                 body <- many (satisfy isMessageBody)                                 pure                                     $ Just                                     $ Message                                         Ghci.Message-                                            { severity = sev-                                            , file = toString fileT-                                            , startPos = sp-                                            , endPos = ep+                                            { severity+                                            , file = Location file+                                            , startPos+                                            , endPos                                             , messageLines = origLine : body                                             }         , -- Fallback: skip any other line@@ -121,13 +123,17 @@     _ <- char '('     _ <- takeWhileP Nothing (== ' ')     filePath <- takeWhile1P Nothing (\c -> c /= ',' && c /= ')')+    let cleanPath = toString (T.stripEnd filePath)+    path <- case Path.fromFilePath @Path.Any cleanPath of+        Left _ -> fail $ "Not a valid file path: " <> cleanPath+        Right path -> pure path     pure         $ Loading             Ghci.Loading                 { Ghci.Loading.index = n                 , Ghci.Loading.total = m                 , Ghci.Loading.moduleName = modName-                , Ghci.Loading.sourceFile = toString (T.stripEnd filePath)+                , Ghci.Loading.sourceFile = path                 }  
src/Tricorder/Daemon/Ghci/LoadResult.hs view
@@ -4,21 +4,23 @@     ) where +import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map import Data.Set qualified as Set -import Tricorder.Build (Diagnostic)+import Tricorder.Build.Diagnostic (Diagnostic) import Tricorder.Daemon.Ghci.LoadedModule (LoadedModule (..))   -- | The result of a GHCi load or reload operation. data LoadResult = LoadResult     { moduleCount :: Int-    , compiledFiles :: Set FilePath+    , compiledFiles :: Set Path.Any     -- ^ Files compiled in this cycle (derived from 'GLoading' items).     -- Used by the session layer to decide which files' previous diagnostics to replace vs. retain.-    , loadedModules :: Map FilePath LoadedModule-    -- ^ Map from canonical absolute path to module metadata, derived from @:show modules@ output.+    , loadedModules :: Map Path.Any LoadedModule+    -- ^ Map from normalised path (as reported by GHCi, so absolute or+    -- project-root-relative) to module metadata, derived from @:show modules@ output.     -- Lists only modules that compiled successfully this cycle — GHCi drops     -- failed-compile modules from @:show modules@.     , targetNames :: [Text]@@ -36,10 +38,10 @@ -- dropped out. Never-compiled targets are absent here (no path↔name -- mapping); the dispatcher recognises those via 'KnownTargetNames'. resolveKnownTargets-    :: Map FilePath LoadedModule+    :: Map Path.Any LoadedModule     -- ^ Previous known-targets map (carryover source).     -> LoadResult-    -> Map FilePath LoadedModule+    -> Map Path.Any LoadedModule resolveKnownTargets prev lr =     let primary = lr.loadedModules         primaryNames = Set.fromList [lm.moduleName | lm <- Map.elems primary]
src/Tricorder/Daemon/Ghci/LoadedModule.hs view
@@ -3,10 +3,12 @@     ) where +import Atelier.FileSystem.Path qualified as Path + -- | A module currently loaded in the GHCi session. data LoadedModule = LoadedModule-    { relPath :: FilePath+    { relPath :: Path.Relative     -- ^ Path relative to the project root (e.g. @"./src/Foo.hs"@).     , moduleName :: Text     }
src/Tricorder/Daemon/Ghci/Loading.hs view
@@ -1,6 +1,8 @@ module Tricorder.Daemon.Ghci.Loading (Loading (..)) where +import Atelier.FileSystem.Path qualified as Path + -- | Payload for a @[N of M] Compiling Mod ( file, ... )@ line. data Loading = Loading     { index :: Int@@ -8,6 +10,6 @@     , total :: Int     -- ^ M (total modules to compile)     , moduleName :: Text-    , sourceFile :: FilePath+    , sourceFile :: Path.Any     }     deriving stock (Eq, Show)
src/Tricorder/Daemon/Ghci/Message.hs view
@@ -1,5 +1,6 @@ module Tricorder.Daemon.Ghci.Message (Message (..)) where +import Tricorder.Build.DiagnosticLocation (DiagnosticLocation) import Tricorder.Daemon.Ghci.Position (Position) import Tricorder.Daemon.Ghci.Severity (Severity) @@ -7,7 +8,7 @@ -- | Payload for a compiler diagnostic (error or warning). data Message = Message     { severity :: Severity-    , file :: FilePath+    , file :: DiagnosticLocation     , startPos :: Position     , endPos :: Position     -- ^ equals 'startPos' when no span
src/Tricorder/Daemon/Ghci/Output.hs view
@@ -9,6 +9,7 @@ import Text.Megaparsec.Char (char) import Prelude hiding (many) +import Atelier.FileSystem.Path qualified as Path import Data.Text qualified as T  import Tricorder.Daemon.Ghci.LineParser (LineParser, LineStream (..))@@ -19,7 +20,7 @@   -- | Parse the output of @:show modules@ into (module name, file path) pairs.-parseShowModules :: [Text] -> [(Text, FilePath)]+parseShowModules :: [Text] -> [(Text, Path.Any)] parseShowModules ls =     case parse (catMaybes <$> many showModuleLine <* eof) "" (LineStream ls) of         Right items -> items@@ -27,20 +28,23 @@   -- | Parse or skip one line of @:show modules@ output.-showModuleLine :: LineParser (Maybe (Text, FilePath))+showModuleLine :: LineParser (Maybe (Text, Path.Any)) showModuleLine = do     line <- anySingle     pure $ TextParser.run showModuleLineP (LineParser.stripAnsi line)  -showModuleLineP :: TextParser (Text, FilePath)+showModuleLineP :: TextParser (Text, Path.Any) showModuleLineP = do     modName <- takeWhile1P Nothing (not . isSpace)     _ <- takeWhileP Nothing (/= '(')     _ <- char '('     _ <- char ' '     filePath <- takeWhile1P Nothing (\c -> c /= ',' && c /= ')')-    pure (modName, toString (T.stripEnd filePath))+    let cleanPath = toString (T.stripEnd filePath)+    case Path.fromFilePath cleanPath of+        Right path -> pure (modName, path)+        Left _ -> fail $ "invalid file path: " <> cleanPath   -- | Parse the output of @:show targets@.
src/Tricorder/Daemon/Ghci/Path.hs view
@@ -4,10 +4,12 @@     ) where -import System.FilePath (dropExtension, normalise, splitDirectories)+import Atelier.FileSystem.Path (Path) +import Atelier.FileSystem.Path qualified as Path import Data.List qualified as List import Data.Text qualified as T+import System.FilePath qualified as P   -- | Whether a diagnostic file is a GHCi location-less pseudo-file — a fully@@ -30,9 +32,9 @@ -- suffix of the path (with @/@ → @.@, extension dropped) is a candidate. -- E.g. @./tricorder/src/Tricorder/Version.hs@ yields candidates -- @"Tricorder.Version"@ and @"Version"@.-pathSuffixesAsModuleName :: FilePath -> [Text]+pathSuffixesAsModuleName :: (Path path) => path -> [Text] pathSuffixesAsModuleName fp =-    let segments = filter (not . null) (splitDirectories (dropExtension (normalise fp)))+    let segments = filter (not . null) $ P.splitDirectories $ P.dropExtension $ P.normalise $ Path.toFilePath fp         upperSegments = dropWhile (not . startsUpper) segments         suffixes = takeWhile (not . null) (iterate (drop 1) upperSegments)     in  [T.intercalate "." (map toText s) | s <- suffixes]
src/Tricorder/Daemon/Ghci/Process.hs view
@@ -16,7 +16,7 @@ where  import Atelier.Effects.Conc (Conc)-import Atelier.Effects.File (BufferMode (..), File, Handle)+import Atelier.Effects.Handles (BufferMode (..), Handle, Handles) import Atelier.Effects.Log (Log) import Atelier.Effects.Process     ( RunningProcess@@ -31,6 +31,7 @@     , shell     ) import Atelier.Effects.Timeout (Timeout)+import Atelier.Time (AsRawUnit (..)) import Control.Concurrent.STM (TVar, modifyTVar', readTVar, retry, writeTVar) import Data.Sequence ((|>)) import Data.Time.Units (Second)@@ -39,11 +40,12 @@ import Effectful.Exception (finally, throwIO, trySync)  import Atelier.Effects.Conc qualified as Conc-import Atelier.Effects.File qualified as File+import Atelier.Effects.Handles qualified as Handles import Atelier.Effects.Log qualified as Log import Atelier.Effects.Process qualified as Atelier import Atelier.Effects.Process qualified as Process import Atelier.Effects.Timeout qualified as Timeout+import Atelier.FileSystem.Path qualified as Path import Data.Text qualified as T  import Tricorder.Daemon.Ghci.Config (Config (..))@@ -105,7 +107,7 @@ setupProcess     :: ( Conc :> es        , Concurrent :> es-       , File :> es+       , Handles :> es        , Log :> es        , Timeout :> es        )@@ -125,9 +127,9 @@     let inp = getStdin p         out = getStdout p         err = getStderr p-    File.hSetBuffering inp LineBuffering-    File.hSetBuffering out LineBuffering-    File.hSetBuffering err LineBuffering+    Handles.hSetBuffering inp LineBuffering+    Handles.hSetBuffering out LineBuffering+    Handles.hSetBuffering err LineBuffering      -- Register the process for interruption before the (possibly slow) banner     -- wait, so an interrupt during @cabal repl@ startup can terminate it.@@ -143,21 +145,21 @@     onReady ghciProcess      -- Send a blank line to kick GHCi into producing output-    File.hPutTextLn inp ""-    File.hFlush inp+    Handles.hPutTextLn inp ""+    Handles.hFlush inp      -- Wait for the version banner. We concurrently capture stderr so that if     -- the build command exits before printing a banner (e.g. cabal's     -- dependency resolution fails) we can surface its error output.-    waitForBannerOrFail config.startupTimeout out err+    waitForBannerOrFail config.startupTimeout.getAsRawUnit out err      -- Send fixed setup commands (protocol requirements)-    File.hPutTextLn inp ":set prompt \"\""-    File.hPutTextLn inp ":set prompt-cont \"\""+    Handles.hPutTextLn inp ":set prompt \"\""+    Handles.hPutTextLn inp ":set prompt-cont \"\""     -- Send any caller-supplied extra setup commands     for_ config.extraSetupCommands \c ->-        File.hPutTextLn inp c-    File.hFlush inp+        Handles.hPutTextLn inp c+    Handles.hFlush inp      -- Sync: drain until marker 1 seen, then set counter to 2.     -- Capture lines from both streams — the stderr output contains the initial@@ -185,10 +187,10 @@ -- action receives the process handle and the output captured during startup. -- See 'setupProcess' for the @onProgress@ and @onReady@ callbacks. with-    :: (Atelier.Process :> es, Conc :> es, Concurrent :> es, File :> es, Log :> es, Timeout :> es)+    :: (Atelier.Process :> es, Conc :> es, Concurrent :> es, Handles :> es, Log :> es, Timeout :> es)     => Config     -> RenderedCommand stage-    -> FilePath+    -> Path.Absolute     -> (Loading -> Eff es ())     -> (Process -> Eff es ())     -> (Process -> [Text] -> Eff es a)@@ -214,7 +216,7 @@ exec     :: ( Conc :> es        , Concurrent :> es-       , File :> es+       , Handles :> es        , Log :> es        )     => Process -> Text -> (Loading -> Eff es ()) -> Eff es [Text]@@ -228,8 +230,8 @@     doExec n = do         let marker = markerFor n             hook = progressLineHook onProgress-        File.hPutTextLn ghciProcess.stdin command-        File.hFlush ghciProcess.stdin+        Handles.hPutTextLn ghciProcess.stdin command+        Handles.hFlush ghciProcess.stdin         sendSyncCommand ghciProcess.stdin marker         -- Scoped so that an exception from one drain (e.g. 'UnexpectedExit'         -- when the underlying process is terminated mid-command) is@@ -256,7 +258,7 @@ -- -- When GHCi is 'Idle' this is a true no-op: sending SIGINT and a sync marker to -- an idle GHCi leaves leftover marker output in the buffers.-interruptGhci :: (Atelier.Process :> es, Concurrent :> es, File :> es) => Process -> Eff es ()+interruptGhci :: (Atelier.Process :> es, Concurrent :> es, Handles :> es) => Process -> Eff es () interruptGhci ghciProcess = do     decision <- atomically do         s <- readTVar ghciProcess.stateVar@@ -285,12 +287,12 @@ -- | Ask GHCi to @:quit@ and wait briefly for it to exit cleanly, letting it -- shut down gracefully before the enclosing 'withProcess' tears down the -- group. Never throws.-quitGhci :: (Atelier.Process :> es, File :> es, Timeout :> es) => Config -> Process -> Eff es ()+quitGhci :: (Atelier.Process :> es, Handles :> es, Timeout :> es) => Config -> Process -> Eff es () quitGhci config ghciProcess = do     void $ trySync $ do-        File.hPutTextLn ghciProcess.stdin ":quit"-        File.hFlush ghciProcess.stdin-    void $ Timeout.with config.shutdownTimeout (Process.waitExitCode ghciProcess.handle)+        Handles.hPutTextLn ghciProcess.stdin ":quit"+        Handles.hFlush ghciProcess.stdin+    void $ Timeout.with config.shutdownTimeout.getAsRawUnit (Process.waitExitCode ghciProcess.handle)   -- ---------------------------------------------------------------------------@@ -320,13 +322,13 @@ -- forever waiting for it (the "stuck Building…" stall). Fully-qualified -- 'System.IO.hPutStrLn' resolves via GHCi's implicit qualified imports even -- with an emptied scope, so the marker survives an interrupt.-sendSyncCommand :: (File :> es) => Handle -> Text -> Eff es ()+sendSyncCommand :: (Handles :> es) => Handle -> Text -> Eff es () sendSyncCommand h marker = do     -- Use show to produce a valid Haskell string literal for the marker text.     let markerLit = toText (show @String (toString marker)) -- e.g. "\"#~TRI-FINISH-3~#\""-    File.hPutTextLn h ("System.IO.hPutStrLn System.IO.stdout " <> markerLit)-    File.hPutTextLn h ("System.IO.hPutStrLn System.IO.stderr " <> markerLit)-    File.hFlush h+    Handles.hPutTextLn h ("System.IO.hPutStrLn System.IO.stdout " <> markerLit)+    Handles.hPutTextLn h ("System.IO.hPutStrLn System.IO.stderr " <> markerLit)+    Handles.hFlush h   -- | Read lines from a handle until /this command's/ finish marker is seen (or@@ -339,11 +341,11 @@ -- Each ordinary line is passed to @onLine@ as it arrives, so callers can stream -- progress without waiting for the full drain to complete. Returns accumulated -- non-marker lines in order. Throws 'UnexpectedExit' on EOF before the marker.-drainUntil :: (File :> es, Log :> es) => Handle -> Text -> (Text -> Eff es ()) -> Eff es [Text]+drainUntil :: (Handles :> es, Log :> es) => Handle -> Text -> (Text -> Eff es ()) -> Eff es [Text] drainUntil h marker onLine = go mempty   where     go acc = do-        result <- trySync $ File.hGetLine h+        result <- trySync $ Handles.hGetLine h         case result of             Left ex -> do                 let accumulatedLines = T.intercalate "\n" $ toList acc@@ -396,7 +398,7 @@ waitForBannerOrFail     :: ( Conc :> es        , Concurrent :> es-       , File :> es+       , Handles :> es        , Timeout :> es        )     => Second -> Handle -> Handle -> Eff es ()@@ -425,7 +427,7 @@                 throwIO $ maybe StartupTimeout StartupFailed (renderCapturedLines captured)  -waitForBannerStdout :: (File :> es) => Handle -> (Text -> Eff es ()) -> Eff es ()+waitForBannerStdout :: (Handles :> es) => Handle -> (Text -> Eff es ()) -> Eff es () waitForBannerStdout h captureLine = go   where     isVersionLine :: Text -> Bool@@ -436,7 +438,7 @@                 || "Clashi, version " `T.isInfixOf` stripped      go = do-        result <- trySync $ File.hGetLine h+        result <- trySync $ Handles.hGetLine h         case result of             Left ex -> throwIO ex             Right line ->@@ -448,11 +450,11 @@                         go  -drainUntilEof :: (File :> es) => Handle -> (Text -> Eff es ()) -> Eff es ()+drainUntilEof :: (Handles :> es) => Handle -> (Text -> Eff es ()) -> Eff es () drainUntilEof h onLine = go   where     go = do-        result <- trySync $ File.hGetLine h+        result <- trySync $ Handles.hGetLine h         case result of             Left _ -> pure ()             Right line -> onLine line >> go@@ -480,10 +482,10 @@ -- Progress is emitted live by 'drainUntil' as lines arrive, so no replay -- callback is needed here — this function only assembles the final result. collectResult-    :: (Conc :> es, Concurrent :> es, File :> es, Log :> es)+    :: (Conc :> es, Concurrent :> es, Handles :> es, Log :> es)     => Process     -> [Text]-    -> FilePath+    -> Path.Absolute     -> Eff es LoadResult collectResult process lines' projectRoot = do     let noProgress = \_ -> pure ()@@ -509,9 +511,9 @@ -- | Execute @:reload@ and return the assembled 'LoadResult'. Progress events -- fire live via @onProgress@ as each @[N of M] Compiling …@ line is read. reload-    :: (Conc :> es, Concurrent :> es, File :> es, Log :> es)+    :: (Conc :> es, Concurrent :> es, Handles :> es, Log :> es)     => Process-    -> FilePath+    -> Path.Absolute     -> (Loading -> Eff es ())     -> Eff es LoadResult reload process projectRoot onProgress = do@@ -522,14 +524,14 @@ -- | Execute @:add@ for the given file and return the assembled 'LoadResult'. -- Progress events fire live via @onProgress@ as compilation proceeds. add-    :: (Conc :> es, Concurrent :> es, File :> es, Log :> es)+    :: (Conc :> es, Concurrent :> es, Handles :> es, Log :> es)     => Process-    -> FilePath -- the file to :add-    -> FilePath -- projectRoot+    -> Path.Any -- the file to :add+    -> Path.Absolute -- projectRoot     -> (Loading -> Eff es ())     -> Eff es LoadResult add process filePath projectRoot onProgress = do-    addLines <- exec process (":add " <> T.pack filePath) onProgress+    addLines <- exec process (":add " <> toText filePath) onProgress     collectResult process addLines projectRoot  @@ -537,10 +539,10 @@ -- 'LoadResult'. Progress events fire live via @onProgress@ as compilation -- proceeds. unadd-    :: (Conc :> es, Concurrent :> es, File :> es, Log :> es)+    :: (Conc :> es, Concurrent :> es, Handles :> es, Log :> es)     => Process     -> Text -- the module name to :unadd-    -> FilePath -- projectRoot+    -> Path.Absolute -- projectRoot     -> (Loading -> Eff es ())     -> Eff es LoadResult unadd process moduleName projectRoot onProgress = do
src/Tricorder/Daemon/Ghci/Result.hs view
@@ -5,22 +5,22 @@     , parseProgressLine     , parseReload     , extractTitle-    , toAbsolute-    , toRelative     ) where +import Atelier.FileSystem.Path ((</>)) import Data.Char (isDigit, isSpace, toLower)-import System.FilePath (isAbsolute, makeRelative, normalise, splitDirectories, (</>)) import Text.Megaparsec import Prelude hiding (many) +import Atelier.FileSystem.Path qualified as Path import Data.List qualified as List import Data.Map.Strict qualified as Map import Data.Set qualified as Set import Data.Text qualified as T -import Tricorder.Build (Diagnostic (..), Severity (..))+import Tricorder.Build.Diagnostic (Diagnostic (..))+import Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..)) import Tricorder.Daemon.Ghci.LineParser (LineStream (..)) import Tricorder.Daemon.Ghci.Load (Load) import Tricorder.Daemon.Ghci.LoadResult (LoadResult (..))@@ -29,12 +29,12 @@ import Tricorder.Daemon.Ghci.Message (Message (..)) import Tricorder.Daemon.Ghci.Position (Position (..)) +import Tricorder.Build.Severity qualified as Build.Severity import Tricorder.Daemon.Ghci.Diagnostic qualified as Diagnostic import Tricorder.Daemon.Ghci.LineParser qualified as LineParser import Tricorder.Daemon.Ghci.Load qualified as Load import Tricorder.Daemon.Ghci.LoadOutcome qualified as LoadOutcome import Tricorder.Daemon.Ghci.Loading qualified as Loading-import Tricorder.Daemon.Ghci.Path qualified as Path import Tricorder.Daemon.Ghci.Severity qualified as Severity import Tricorder.Daemon.Ghci.TextParser qualified as TextParser @@ -75,43 +75,28 @@ -- Pure utilities (unchanged) -- --------------------------------------------------------------------------- --- | Make an absolute path relative to the given base directory, prefixed with @"./"@.--- Paths already relative, or absolute paths outside @base@, are returned unchanged.-toRelative :: FilePath -> FilePath -> FilePath-toRelative base path-    | not (isAbsolute path) = path-    | otherwise = case splitDirectories (makeRelative base path) of-        (".." : _) -> path-        rel -> "." </> List.foldr1 (</>) rel----- | Make a relative path absolute by prepending the given base directory.--- Paths already absolute are returned unchanged.-toAbsolute :: FilePath -> FilePath -> FilePath-toAbsolute base path-    | isAbsolute path = path-    | otherwise = base </> path-- -- | Assemble a 'LoadResult' from a project root, parsed reload items, the -- @:show modules@ output, and the @:show targets@ output.-collectResultCustom :: FilePath -> [Load] -> [(Text, FilePath)] -> [Text] -> LoadResult+collectResultCustom :: Path.Absolute -> [Load] -> [(Text, Path.Any)] -> [Text] -> LoadResult collectResultCustom projectRoot loads modules targets =-    let rel = toRelative projectRoot-        abs' = toAbsolute projectRoot+    let rel (Path.Relative p) = p+        rel (Path.Absolute p) = (Path.relative @"." </>) . Path.makeRelative projectRoot $ p         compiledFiles = case [l.sourceFile | Load.Loading l <- loads] of-            [] -> Set.fromList (map (rel . snd) modules)-            fs -> Set.fromList (map rel fs)-        mkEntry (mn, fp) =-            ( normalise (abs' fp)-            , LoadedModule {relPath = rel fp, moduleName = mn}+            [] -> Set.fromList (map snd modules)+            fs -> Set.fromList fs+        mkEntry (mn, (fp :: Path.Any)) =+            ( Path.normalise fp+            , LoadedModule+                { relPath = rel fp+                , moduleName = mn+                }             )     in  LoadResult             { moduleCount = length modules             , compiledFiles             , loadedModules = Map.fromList (map mkEntry modules)             , targetNames = targets-            , diagnostics = toDiagnostics rel loads+            , diagnostics = toDiagnostics loads             }  @@ -123,11 +108,11 @@ -- location-less failure we don't otherwise attribute to a file), a synthetic -- error diagnostic is appended so the build can never be reported as clean -- while GHCi considers it failed.-collectResult :: FilePath -> [Text] -> [(Text, FilePath)] -> [Text] -> LoadResult+collectResult :: Path.Absolute -> [Text] -> [(Text, Path.Any)] -> [Text] -> LoadResult collectResult projectRoot reloadLines modules targets =     let loads = parseReload reloadLines         base = collectResultCustom projectRoot loads modules targets-        hasError = any (\d -> d.severity == SError) base.diagnostics+        hasError = any (\d -> d.severity == Build.Severity.Error) base.diagnostics     in  if reloadFailed loads && not hasError             then                 base {diagnostics = base.diagnostics ++ [Diagnostic.unattributedFailure]}@@ -150,22 +135,22 @@         outcomes -> List.last outcomes == LoadOutcome.LoadFailed  -toDiagnostics :: (FilePath -> FilePath) -> [Load] -> [Diagnostic]-toDiagnostics rel loads = mapMaybe toMsg loads+toDiagnostics :: [Load] -> [Diagnostic]+toDiagnostics loads = mapMaybe toMsg loads   where     -- Location-less messages (e.g. @<no location info>@, @<interactive>@) carry     -- no source span. We keep the *errors* — a @<no location info>@ error is a     -- genuine load failure (e.g. a home-unit GHC plugin that can't be loaded in     -- @--enable-multi-repl@) and must not be silently dropped — but discard     -- location-less warnings, which are just noise without a file to attach to.-    toMsg (Load.Message m) | Path.isLocationLess m.file, m.severity /= Severity.Error = Nothing+    toMsg (Load.Message m) | Locationless <- m.file, m.severity /= Severity.Error = Nothing     toMsg (Load.Message m) =         Just             Diagnostic                 { severity = case m.severity of-                    Severity.Warning -> SWarning-                    Severity.Error -> SError-                , file = rel m.file+                    Severity.Warning -> Build.Severity.Warning+                    Severity.Error -> Build.Severity.Error+                , file = m.file                 , line = m.startPos.line                 , col = m.startPos.col                 , endLine = m.endPos.line
src/Tricorder/Daemon/Ghci/Session.hs view
@@ -10,7 +10,7 @@ where  import Atelier.Effects.Conc (Conc)-import Atelier.Effects.File (File)+import Atelier.Effects.Handles (Handles) import Atelier.Effects.Log (Log) import Atelier.Effects.Process (Process) import Atelier.Effects.Timeout (Timeout)@@ -34,14 +34,14 @@ import Effectful.State.Static.Shared (State, evalState, state) import Effectful.TH (makeEffect) -import Tricorder.Build (BuildProgress (..)) import Tricorder.Daemon.Ghci.Controls (Controls (..)) import Tricorder.Daemon.Ghci.LoadResult (LoadResult) import Tricorder.Daemon.Ghci.Loading (Loading (..))-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.Command.RenderedCommand (RenderedCommand) import Tricorder.Session.Stage (Stage (..)) +import Tricorder.Build.Progress qualified as Build (Progress (..)) import Tricorder.Daemon.Ghci.Controls qualified as Controls import Tricorder.Daemon.Ghci.Process qualified as Ghci.Process import Tricorder.Daemon.Ghci.Process qualified as Process@@ -53,7 +53,7 @@     -- returning new messages with module counts. The GHCi session is closed     -- when the handler returns.     With-        :: (BuildProgress -> m ())+        :: (Build.Progress -> m ())         -- ^ Action to run when reporting progress         -> RenderedCommand 'Build         -> ProjectRoot@@ -101,7 +101,7 @@ run     :: ( Conc :> es        , Concurrent :> es-       , File :> es+       , Handles :> es        , Log :> es        , Process :> es        , Timeout :> es@@ -114,7 +114,7 @@                 let reportProgress loading =                         unlift                             $ onProgress-                            $ BuildProgress+                            $ Build.Progress                                 { compiled = loading.index                                 , total = loading.total                                 }
src/Tricorder/Daemon/HookDispatch.hs view
@@ -1,16 +1,18 @@ module Tricorder.Daemon.HookDispatch (main) where +import Atelier.Effects.Log (Log) import Atelier.Effects.Process (Process) import Atelier.Effects.PubSub.Sub (Sub) import Effectful.Reader.Static (Reader)  import Atelier.Effects.FileWatcher.Event qualified as FileWatcher import Atelier.Effects.FileWatcher.Event qualified as FileWatcher.Event+import Atelier.Effects.Log qualified as Log import Atelier.Effects.PubSub.Sub qualified as Sub-import System.FilePath qualified as Path+import Atelier.FileSystem.Path qualified as Path  import Tricorder.Daemon.Watch (WatchedFile (..))-import Tricorder.Runtime (ProjectRoot)+import Tricorder.Runtime.ProjectRoot (ProjectRoot) import Tricorder.Session (Session (..)) import Tricorder.Session.HaskellHooks (HaskellHooks (..)) import Tricorder.Session.Hooks (Hooks (..))@@ -18,19 +20,32 @@ import Tricorder.Session.Hook qualified as Hook  -main :: (Process :> es, Reader ProjectRoot :> es, Sub WatchedFile :> es) => Session -> Eff es Void+main+    :: ( Log :> es+       , Process :> es+       , Reader ProjectRoot :> es+       , Sub WatchedFile :> es+       )+    => Session -> Eff es Void main session =     Sub.listen_ \case         (WatchedFile path event)-            | Path.takeExtension path == "hs"+            | Path.takeExtension path == ".hs"             , Just hooks <- session.hooks.haskell ->                 runHsHook hooks event             | otherwise -> pure ()   runHsHook-    :: (Process :> es, Reader ProjectRoot :> es) => HaskellHooks -> FileWatcher.Event -> Eff es ()+    :: (Log :> es, Process :> es, Reader ProjectRoot :> es)+    => HaskellHooks -> FileWatcher.Event -> Eff es () runHsHook hooks = \case-    FileWatcher.Event.Added -> whenJust hooks.fileAdded Hook.run-    FileWatcher.Event.Modified -> whenJust hooks.fileModified Hook.run-    FileWatcher.Event.Removed -> whenJust hooks.fileRemoved Hook.run+    FileWatcher.Event.Added -> whenJust hooks.fileAdded \hook -> do+        Log.debug "Running Haskell file added hook"+        Hook.run hook+    FileWatcher.Event.Modified -> whenJust hooks.fileModified \hook -> do+        Log.debug "Running Haskell file modified hook"+        Hook.run hook+    FileWatcher.Event.Removed -> whenJust hooks.fileRemoved \hook -> do+        Log.debug "Running Haskell file removed hook"+        Hook.run hook
src/Tricorder/Daemon/Hpack.hs view
@@ -7,6 +7,7 @@ import Atelier.Effects.FileWatcher (FileWatcher) import Atelier.Effects.Log (Log) import Atelier.Effects.PubSub.Pub (Pub)+import Atelier.FileSystem.Path ((</>)) import Effectful.Reader.Static (Reader)  import Atelier.Effects.Conc qualified as Conc@@ -16,11 +17,11 @@ import Atelier.Effects.PubSub qualified as PubSub import Atelier.Effects.PubSub.Pub qualified as Pub import Atelier.Effects.PubSub.Sub qualified as Sub-import Data.List qualified as List+import Atelier.FileSystem.Path qualified as Path import Effectful.Reader.Static qualified as Reader  import Tricorder.Daemon.Hpack.Effect (Hpack)-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session (Session (..)) import Tricorder.Session.GenerateWithHpack (GenerateWithHpack (..)) @@ -47,7 +48,7 @@             vacuous $ watchPackageYaml projectRoot  -runHpack :: (Hpack :> es, Log :> es) => FilePath -> Eff es ()+runHpack :: (Hpack :> es, Log :> es) => Path.Absolute -> Eff es () runHpack path = do     res <- Hpack.hpack path     case res of@@ -74,12 +75,15 @@     => ProjectRoot -> Eff es Void watchPackageYaml root = do     FileWatcher.watchFilePathsDebounced-        [FileWatcher.Watch.dirWhere root.getProjectRoot (packageYaml `List.isSuffixOf`)]-        \path _ -> Pub.publish $ RePack path+        [FileWatcher.Watch.dirWhere root.getProjectRoot (packageYaml `Path.isSuffixOf`)]+        \path _ -> case Path.fromFilePath path of+            Right (Path.Absolute parsedPath) -> Pub.publish $ RePack parsedPath+            Right (Path.Relative parsedPath) -> Pub.publish $ RePack $ root.getProjectRoot </> parsedPath+            _ -> pure ()  -data RePack = RePack FilePath+data RePack = RePack Path.Absolute  -packageYaml :: FilePath-packageYaml = "package.yaml"+packageYaml :: Path.Relative+packageYaml = Path.relative @"package.yaml"
src/Tricorder/Daemon/Hpack/Effect.hs view
@@ -14,13 +14,13 @@ import Effectful.TH (makeEffect) import System.Exit (ExitCode (..)) +import Atelier.FileSystem.Path qualified as Path import Data.ByteString.Char8 qualified as B8-import System.FilePath qualified as Path   data Hpack :: Effect where     HpackIsInPath :: Hpack m Bool-    Hpack :: FilePath -> Hpack m (Either Text Result)+    Hpack :: Path.Absolute -> Hpack m (Either Text Result)   data Result
src/Tricorder/Daemon/Main.hs view
@@ -13,10 +13,9 @@ import Atelier.Effects.Env qualified as Env import Atelier.Effects.Exit qualified as Exit import Atelier.Effects.FSNotify qualified as FSNotify-import Atelier.Effects.File qualified as File-import Atelier.Effects.FileSystem qualified as FileSystem import Atelier.Effects.FileSystem.Glob qualified as Glob import Atelier.Effects.FileWatcher qualified as FileWatcher+import Atelier.Effects.Handles qualified as Handles import Atelier.Effects.Input qualified as Input import Atelier.Effects.Log qualified as Log import Atelier.Effects.Process qualified as Process@@ -24,19 +23,19 @@ import Atelier.Effects.PubSub.Pub qualified as Pub import Atelier.Effects.PubSub.Sub qualified as Sub import Atelier.Effects.Timeout qualified as Timeout+import Effectful.FileSystem qualified as FileSystem import Effectful.Reader.Static qualified as Reader import Effectful.State.Static.Shared qualified as State -import Tricorder.Build (BuildId (..), BuildPhase)-import Tricorder.Build.Changes (CabalChangeDetected, SourceChangeDetected)+import Tricorder.Build.Changes (ProjectChangeDetected, SourceChangeDetected) import Tricorder.Config (asInput) import Tricorder.Daemon.Watch (WatchedFile)-import Tricorder.Logging (runLogging)-import Tricorder.Runtime (runLogPath, runProjectRoot, runRuntimeDir, runSocketPath) import Tricorder.Session.CabalFile (inputCabalFiles) import Tricorder.SourceLookup.GhcPkg (runGhcPkgIO) -import Tricorder.Build qualified as BuildPhase+import Tricorder.Build.Id qualified as Build (Id (..))+import Tricorder.Build.Phase qualified as Build (Phase)+import Tricorder.Build.Phase qualified as Build.Phase import Tricorder.Config.LoadedConfig qualified as LoadedConfig import Tricorder.Daemon.Core qualified as Core import Tricorder.Daemon.EvalCommentRunner qualified as EvalCommentRunner@@ -47,6 +46,13 @@ import Tricorder.Daemon.IdleTimer qualified as IdleTimer import Tricorder.Daemon.TestRunner qualified as TestRunner import Tricorder.Daemon.Watch qualified as Watch+import Tricorder.Logging qualified as Logging+import Tricorder.Runtime.Cache qualified as Runtime.Cache+import Tricorder.Runtime.Directory qualified as Runtime.Directory+import Tricorder.Runtime.LogPath qualified as Runtime.LogPath+import Tricorder.Runtime.ProjectHash qualified as Runtime.ProjectHash+import Tricorder.Runtime.ProjectRoot qualified as Runtime.ProjectRoot+import Tricorder.Runtime.SocketPath qualified as Runtime.SocketPath import Tricorder.Session qualified as Session import Tricorder.Session.StackProject qualified as StackProject import Tricorder.Session.State qualified as Session.State@@ -62,24 +68,26 @@ main =     runEff         . runConcurrent+        . FileSystem.runFileSystem         . Conc.runIO         . Clock.runIO         . Delay.runIO         . Timeout.run         . Debounce.run @FilePath-        . FileSystem.runIO         . FSNotify.run-        . FileWatcher.runIO         . Glob.runIO-        . runProjectRoot-        . Exit.runIO-        . File.run-        . runRuntimeDir-        . runSocketPath-        . runLogPath         . Env.runIO+        . Exit.runIO+        . Runtime.ProjectRoot.asReader+        . Runtime.ProjectHash.asReader+        . Runtime.Cache.asReader+        . Runtime.LogPath.asReader         . LoadedConfig.asInput-        . runLogging+        . Handles.run+        . Logging.run+        . FileWatcher.runIO+        . Runtime.Directory.asReader+        . Runtime.SocketPath.asReader         . Chan.run         . StackProject.inputWithCache         . inputCabalFiles@@ -87,14 +95,14 @@         . runGhcPkgIO         . UnixSocket.runIO         . Ghci.Session.run-        . State.evalState (BuildId 1)-        . Input.fromState @BuildId+        . State.evalState (Build.Id 1)+        . Input.fromState @Build.Id         . Hpack.run         . EvalCommentRunner.run         . TestRunner.run         . Waiters.run-        . PubSub.run @BuildPhase-        . PubSub.run @CabalChangeDetected+        . PubSub.run @Build.Phase+        . PubSub.run @ProjectChangeDetected         . PubSub.run @SourceChangeDetected         . PubSub.run @WatchedFile         . Tricorder.Config.asInput@@ -118,7 +126,7 @@                                 "Unable to start builder due to invalid session: "                                     <> Session.State.Result.Invalid.reason invalid                         Log.err msg-                        Pub.publish $ BuildPhase.Failed msg+                        Pub.publish $ Build.Phase.Failed msg                     Session.State.Result.Ok session -> do                         void $ Conc.fork $ Hpack.main session                         Conc.fork_ $ HookDispatch.main session
src/Tricorder/Daemon/TestRunner.hs view
@@ -17,7 +17,7 @@ where  import Atelier.Effects.Conc (Conc)-import Atelier.Effects.File (File)+import Atelier.Effects.Handles (Handles) import Atelier.Effects.Log (Log) import Atelier.Effects.Process     ( Process@@ -47,7 +47,7 @@ import System.Exit (ExitCode (..))  import Atelier.Effects.Conc qualified as Conc-import Atelier.Effects.File qualified as File+import Atelier.Effects.Handles qualified as Handles import Atelier.Effects.Process qualified as Process import Atelier.Effects.Timeout qualified as Timeout import Atelier.Time qualified as Time@@ -55,7 +55,7 @@ import Data.Text qualified as T  import Tricorder.Daemon.Ghci.Loading (Loading (..))-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.Command.RenderedCommand (RenderedCommand (..)) import Tricorder.Session.Stage (Stage (..)) import Tricorder.Session.Stage.Test.Command (RenderedTestCommand (..))@@ -89,7 +89,7 @@ run     :: ( Conc :> es        , Concurrent :> es-       , File :> es+       , Handles :> es        , Log :> es        , Process :> es        , Reader ProjectRoot :> es@@ -109,7 +109,7 @@ runTestSuiteWithStdout     :: ( Conc :> es        , Concurrent :> es-       , File :> es+       , Handles :> es        , Process :> es        , Reader ProjectRoot :> es        , Timeout :> es@@ -131,15 +131,15 @@                 $ toString cmd.getRenderedCommand          drain h =-            unlessM (File.hIsEOF h) do-                line <- File.hGetLine h+            unlessM (Handles.hIsEOF h) do+                line <- Handles.hGetLine h                 atomically $ modifyTVar' outputVar (|> line)                 traverse_ onProgress (Ghci.Result.parseProgressLine line)                 drain h          runToCompletion p = do             -- The suite gets no input; close stdin so it sees EOF if it reads.-            File.hClose (getStdin p)+            Handles.hClose (getStdin p)             Conc.scoped do                 stdoutThread <- Conc.fork $ drain (getStdout p)                 stderrThread <- Conc.fork $ drain (getStderr p)@@ -149,7 +149,7 @@      result <- trySync         $ Process.withProcessGroup processConfig \p ->-            case Time.convertUnit @_ @Second session.options.timeout of+            case Time.convertUnit @_ @Second session.options.timeout.getAsRawUnit of                 secs | secs <= 0 -> Right <$> runToCompletion p                 secs -> maybeToRight secs <$> Timeout.with secs (runToCompletion p)     output <- T.unlines . toList <$> readTVarIO outputVar@@ -181,7 +181,7 @@ runTestSuiteWithGHCi     :: ( Conc :> es        , Concurrent :> es-       , File :> es+       , Handles :> es        , Log :> es        , Process :> es        , Reader ProjectRoot :> es@@ -195,7 +195,7 @@     ProjectRoot projectRoot <- ask     result <- trySync         $ Ghci.Process.with session.ghci cmd projectRoot onProgress noReady \ghci _ ->-            case Time.convertUnit @_ @Second session.options.timeout of+            case Time.convertUnit @_ @Second session.options.timeout.getAsRawUnit of                 secs | secs <= 0 -> Right <$> Ghci.Process.exec ghci ":main" noProgress                 secs ->                     maybeToRight secs
src/Tricorder/Daemon/Watch.hs view
@@ -3,14 +3,15 @@     , files     , publishChange     , specs-    , isCabalFile+    , isProjectFile     ) where  import Atelier.Effects.Debounce (Debounce) import Atelier.Effects.FileWatcher (FileWatcher)+import Atelier.Effects.Log (Log) import Atelier.Effects.PubSub.Pub (Pub)-import System.FilePath (takeExtension, takeFileName)+import Atelier.FileSystem.Path (Path) import Text.Regex.TDFA (ExecOption (..), blankCompOpt, blankExecOpt, match) import Text.Regex.TDFA.TDFA (patternToRegex) @@ -18,21 +19,23 @@ import Atelier.Effects.FileWatcher.Event qualified as FileWatcher (Event) import Atelier.Effects.FileWatcher.Watch qualified as FileWatcher (Watch) import Atelier.Effects.FileWatcher.Watch qualified as Watch+import Atelier.Effects.Log qualified as Log import Atelier.Effects.PubSub.Pub qualified as Pub+import Atelier.FileSystem.Path qualified as Path  import Tricorder.Build.Changes-    ( CabalChangeDetected (..)-    , ChangeKind (..)+    ( ChangeKind (..)+    , ProjectChangeDetected (..)     , SourceChangeDetected (..)     )-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session (Session (..)) import Tricorder.Session.WatchDirs (WatchDirs (..))-import Tricorder.Session.WatchExclusionPatterns (Pattern, WatchExclusionPatterns (..))+import Tricorder.Session.WatchExclusionPatterns (Pattern (..), WatchExclusionPatterns (..))   data WatchedFile = WatchedFile-    { path :: FilePath+    { path :: Path.Any     , event :: FileWatcher.Event     } @@ -40,40 +43,43 @@ files     :: ( Debounce FilePath :> es        , FileWatcher :> es+       , Log :> es        , Pub WatchedFile :> es        )     => ProjectRoot -> Session -> Eff es Void files projectRoot session =     FileWatcher.watchFilePathsDebounced watches \filePath fileEvent ->-        Pub.publish $ WatchedFile filePath fileEvent+        case Path.fromFilePath filePath of+            Right path -> Pub.publish $ WatchedFile path fileEvent+            Left err -> Log.warn $ "Received invalid file path for watched file: " <> err   where     watches = specs projectRoot session.watchExclusionPatterns session.watchDirs   publishChange-    :: ( Pub CabalChangeDetected :> es+    :: ( Pub ProjectChangeDetected :> es        , Pub SourceChangeDetected :> es        )     => WatchedFile -> Eff es () publishChange f =     case changeKindFor f.path of-        CabalChange -> Pub.publish (CabalChangeDetected f.path f.event)-        SourceChange -> Pub.publish (SourceChangeDetected f.path f.event)+        ProjectChange -> Pub.publish $ ProjectChangeDetected f.path f.event+        SourceChange -> Pub.publish $ SourceChangeDetected f.path f.event  -changeKindFor :: FilePath -> ChangeKind+changeKindFor :: (Path path) => path -> ChangeKind changeKindFor path-    | isCabalFile path = CabalChange+    | isProjectFile path = ProjectChange     | otherwise = SourceChange   specs :: ProjectRoot -> WatchExclusionPatterns -> WatchDirs -> [FileWatcher.Watch] specs projectRoot watchExclusionPatterns watchDirs =     sourceWatches (coerce watchExclusionPatterns) (coerce watchDirs)-        <> cabalWatches projectRoot+        <> projectWatches projectRoot  -sourceWatches :: [Pattern] -> [FilePath] -> [FileWatcher.Watch]+sourceWatches :: [Pattern] -> [Path.Absolute] -> [FileWatcher.Watch] sourceWatches exclusionPatterns =     map \d ->         Watch.dirExt d ".hs"@@ -81,23 +87,34 @@             `Watch.excluding` exclusionMatches exclusionPatterns  -exclusionMatches :: [Pattern] -> FilePath -> Bool-exclusionMatches exclusionPatterns fp = any matchPattern exclusionPatterns+exclusionMatches :: [Pattern] -> Path.Absolute -> Bool+exclusionMatches exclusionPatterns fp =+    any matchPattern exclusionPatterns   where-    matchPattern p =+    matchPattern (Pattern p) =         match             (patternToRegex p blankCompOpt blankExecOpt {captureGroups = False})-            fp+            $ Path.toFilePath fp  -cabalWatches :: ProjectRoot -> [FileWatcher.Watch]-cabalWatches (ProjectRoot projectRoot) =-    [ Watch.dirWhere projectRoot isCabalFile+projectWatches :: ProjectRoot -> [FileWatcher.Watch]+projectWatches (ProjectRoot projectRoot) =+    [ Watch.dirWhere projectRoot isProjectFile         `Watch.excluding` Watch.containing "dist-newstyle"     ]  -isCabalFile :: FilePath -> Bool-isCabalFile f =-    takeExtension f == ".cabal"-        || takeFileName f `elem` ["cabal.project", "package.yaml"]+isProjectFile :: (Path path) => path -> Bool+isProjectFile f =+    Path.takeExtension f == ".cabal"+        || Path.toFilePath (Path.takeFileName f)+            -- We explicitly do not watch for changes to `package.yaml`, since+            -- changes to `package.yaml` would result in changes to `.cabal`+            -- files, which would just end up causing the builder to restart+            -- twice, once for `package.yaml` and once for the corresponding+            -- `.cabal` file.+            `elem` [ "cabal.project"+                   , "cabal.project.local"+                   , "cabal.project.freeze"+                   , "stack.yaml"+                   ]
src/Tricorder/Logging.hs view
@@ -1,34 +1,42 @@-module Tricorder.Logging (runLogging) where+module Tricorder.Logging (run) where  import Atelier.Effects.Env (Env)-import Atelier.Effects.File (BufferMode (..), File)+import Atelier.Effects.Handles (BufferMode (..), Handles) import Atelier.Effects.Input (Input) import Atelier.Effects.Log (Log, Severity (..)) import Effectful (IOE)-import Effectful.Reader.Static (Reader, asks)+import Effectful.Exception (trySync)+import Effectful.FileSystem (FileSystem)+import Effectful.Reader.Static (Reader) -import Atelier.Effects.File qualified as File+import Atelier.Effects.Env qualified as Env+import Atelier.Effects.Handles qualified as Handles import Atelier.Effects.Input qualified as Input import Atelier.Effects.Log qualified as Log+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path+import Effectful.Reader.Static qualified as Reader  import Tricorder.Config.LoadedConfig (LoadedConfig)-import Tricorder.Runtime (LogPath (..))+import Tricorder.Runtime.LogPath (LogPath (..))  import Tricorder.Config.LoadedConfig qualified as LoadedConfig  -runLogging+run     :: ( Env :> es-       , File :> es+       , FileSystem :> es+       , Handles :> es        , IOE :> es        , Input LoadedConfig :> es        , Reader LogPath :> es        )     => Eff (Log : es) a -> Eff es a-runLogging act = do-    path <- asks @LogPath (.getLogPath)-    File.with path AppendMode \h -> do-        File.hSetBuffering h LineBuffering+run act = do+    LogPath path <- Reader.ask+    truncateLog path+    Handles.with path AppendMode \h -> do+        Handles.hSetBuffering h LineBuffering         (maybeErr, sev) <- getMinimumSeverity         Log.runToHandle h sev do             whenJust maybeErr \err -> Log.err err@@ -51,3 +59,16 @@                     pure (Just $ "failed to parse log config: " <> err, Log.INFO)                 Right cfg ->                     pure (Nothing, cfg.minimumSeverity)+++noTruncateVarName :: String+noTruncateVarName = "TRICORDER_NO_LOG_TRUNCATE"+++truncateLog+    :: (Env :> es, FileSystem :> es)+    => Path.Absolute -> Eff es ()+truncateLog path = do+    doTruncate <- (\x -> x == Nothing || x == Just "0") <$> Env.lookup noTruncateVarName+    when doTruncate do+        void $ trySync $ File.write path ("" :: ByteString)
− src/Tricorder/Runtime.hs
@@ -1,96 +0,0 @@-module Tricorder.Runtime-    ( PidFile (..)-    , runPidFile-    , ProjectRoot (..)-    , runProjectRoot-    , RuntimeDir (..)-    , runRuntimeDir-    , runRuntimeDirItem-    , SocketPath (..)-    , runSocketPath-    , LogPath (..)-    , runLogPath-    )-where--import Atelier.Effects.FileSystem-    ( FileSystem-    , canonicalizePath-    , createDirectoryIfMissing-    , getCurrentDirectory-    , getXdgRuntimeDir-    )-import Atelier.Effects.Posix.Daemons (PidFile (..))-import Effectful.Reader.Static (Reader, ask, runReader)-import Numeric (showHex)-import System.FilePath ((</>))---newtype SocketPath = SocketPath {getSocketPath :: FilePath}---runSocketPath-    :: (Reader RuntimeDir :> es)-    => Eff (Reader SocketPath : es) a-    -> Eff es a-runSocketPath = runRuntimeDirItem "socket.sock" SocketPath---newtype RuntimeDir = RuntimeDir {getRuntimeDir :: FilePath}---runRuntimeDir-    :: ( FileSystem :> es-       , Reader ProjectRoot :> es-       )-    => Eff (Reader RuntimeDir : es) a -> Eff es a-runRuntimeDir act = do-    ProjectRoot projectRoot <- ask-    runtimeDir <- getXdgRuntimeDir-    canonProjectRoot <- canonicalizePath projectRoot-    let projectDirHash = hashPath canonProjectRoot-        dir = runtimeDir </> "tricorder" </> projectDirHash-    createDirectoryIfMissing True dir-    runReader (RuntimeDir dir) act---runRuntimeDirItem-    :: (Reader RuntimeDir :> es)-    => FilePath-    -- ^ Path segment to append to runtime dir.-    -> (FilePath -> a)-    -- ^ Constructor for the resulting type.-    -> Eff (Reader a : es) b-    -> Eff es b-runRuntimeDirItem path mk act = do-    RuntimeDir runtimeDir <- ask-    runReader (mk $ runtimeDir </> path) act---newtype ProjectRoot = ProjectRoot {getProjectRoot :: FilePath}---runProjectRoot-    :: (FileSystem :> es, HasCallStack)-    => Eff (Reader ProjectRoot : es) a -> Eff es a-runProjectRoot act = do-    projectRoot <- getCurrentDirectory-    runReader (ProjectRoot projectRoot) act---runPidFile :: (Reader RuntimeDir :> es) => Eff (Reader PidFile : es) a -> Eff es a-runPidFile = runRuntimeDirItem "daemon.pid" PidFile---newtype LogPath = LogPath {getLogPath :: FilePath}---runLogPath :: (Reader RuntimeDir :> es) => Eff (Reader LogPath : es) a -> Eff es a-runLogPath = runRuntimeDirItem "daemon.log" LogPath----- | Polynomial hash of a file path, returned as a hex string.-hashPath :: FilePath -> String-hashPath path =-    let n = foldl' (\acc c -> acc * 31 + toInteger (ord c)) (0 :: Integer) path-    in  showHex (abs n `mod` (16 ^ (16 :: Integer))) ""
+ src/Tricorder/Runtime/Cache.hs view
@@ -0,0 +1,60 @@+module Tricorder.Runtime.Cache+    ( Cache (..)+    , asReader+    )+where++import Atelier.Effects.Env (Env)+import Atelier.Effects.Exit (Exit)+import Atelier.FileSystem.Path ((</>))+import Atelier.FileSystem.Permissions (Permissions (..))+import Data.Aeson (FromJSON, ToJSON)+import Effectful.Exception (trySync)+import Effectful.FileSystem (FileSystem)+import Effectful.Reader.Static (Reader)++import Atelier.Effects.Env qualified as Env+import Atelier.Effects.Exit qualified as Exit+import Atelier.FileSystem.Directory qualified as Directory+import Atelier.FileSystem.Path qualified as Path+import Atelier.FileSystem.Permissions qualified as Permissions+import Effectful.Reader.Static qualified as Reader++import Tricorder.Runtime.ProjectHash (ProjectHash (..))+++newtype Cache = Cache {getCache :: Path.Absolute}+    deriving stock (Eq, Generic, Show)+    deriving (FromJSON, ToJSON) via Path.Absolute+++envName :: String+envName = "TRICORDER_CACHE_DIR"+++asReader+    :: (Env :> es, Exit :> es, FileSystem :> es, Reader ProjectHash :> es)+    => Eff (Reader Cache : es) a -> Eff es a+asReader act = do+    mCachePath <- Env.lookup envName+    case mCachePath of+        Just cachePath+            | Right path <- Path.fromFilePath cachePath ->+                Reader.runReader (Cache path) act+        _ -> do+            ProjectHash projectHash <- Reader.ask+            dir <- Directory.getXdg Directory.XdgCache $ Path.rel @"tricorder" </> projectHash+            mDir <- mkUsable dir+            case mDir of+                Nothing -> Exit.with $ Exit.ExitFailure 255+                Just d -> Reader.runReader (Cache d) act+++mkUsable :: (FileSystem :> es) => Path.Absolute -> Eff es (Maybe Path.Absolute)+mkUsable path =+    fmap (either (const Nothing) Just) $ trySync do+        Directory.createIfMissing True path+        permissions <- Permissions.get path+        unless (Permissions.writable permissions) do+            Permissions.set path $ permissions {writable = True}+        pure path
+ src/Tricorder/Runtime/Directory.hs view
@@ -0,0 +1,106 @@+module Tricorder.Runtime.Directory+    ( Directory (..)+    , asReader+    , asReaderFor+    )+where++import Atelier.Effects.Env (Env)+import Atelier.Effects.Exit (Exit)+import Atelier.Effects.Log (Log)+import Atelier.FileSystem.Path ((</>))+import Effectful.Exception (trySync)+import Effectful.FileSystem (FileSystem)+import Effectful.NonDet (emptyEff, plusEff)+import Effectful.Reader.Static (Reader)++import Atelier.Effects.Env qualified as Env+import Atelier.Effects.Exit qualified as Exit+import Atelier.Effects.Log qualified as Log+import Atelier.FileSystem.Directory qualified as Directory+import Atelier.FileSystem.Path qualified as Path+import Atelier.FileSystem.Permissions qualified as Permissions+import Effectful.NonDet qualified as NonDet+import Effectful.Reader.Static qualified as Reader++import Tricorder.Runtime.ProjectHash (ProjectHash (..))+++newtype Directory = Directory {getDirectory :: Path.Absolute}+++asReader+    :: ( Env :> es+       , Exit :> es+       , FileSystem :> es+       , Log :> es+       , Reader ProjectHash :> es+       )+    => Eff (Reader Directory : es) a -> Eff es a+asReader act = do+    ProjectHash projectDirHash <- Reader.ask+    let subDir = Path.relative @"tricorder" </> projectDirHash+        fallback = do+            res <- mkUsable $ Path.abs @"/tmp" </> subDir+            case res of+                Just d -> pure d+                Nothing -> do+                    Log.err+                        "Could not create a writable directory in XDG_RUNTIME_DIR, XDG_STATE_HOME nor int he temporary directory. Tricorder cannot contact the daemon without creating a socket file."+                    Exit.failure+    dir <-+        (either (const fallback) pure)+            <=< NonDet.runNonDet NonDet.OnEmptyKeep+            $ xdgRuntimeCandidate subDir+                `plusEff` xdgStateCandidate subDir+                `plusEff` temporaryCandidate subDir+    Reader.runReader (Directory dir) act+  where+    xdgRuntimeCandidate dir' = do+        runtimeDir <- Env.lookup "XDG_RUNTIME_DIR"+        case runtimeDir of+            Just d | Right path <- Path.fromFilePath d -> do+                usable <- mkUsable $ path </> dir'+                case usable of+                    Just valid -> pure valid+                    Nothing -> emptyEff+            _ -> emptyEff+    xdgStateCandidate dir' = do+        res <- trySync $ Directory.getXdg Directory.XdgState dir'+        case res of+            Right path -> do+                usable <- mkUsable path+                case usable of+                    Just valid -> pure valid+                    Nothing -> emptyEff+            Left _ -> emptyEff+    temporaryCandidate dir' = do+        res <- trySync Directory.getTemporary+        case res of+            Right path -> do+                usable <- mkUsable $ path </> dir'+                case usable of+                    Just valid -> pure valid+                    Nothing -> emptyEff+            Left _ -> emptyEff++    mkUsable dir = do+        r <- trySync do+            Directory.createIfMissing True dir+            Permissions.get dir+        case r of+            Right permissions | Permissions.writable permissions -> pure $ Just dir+            _ -> pure Nothing+++asReaderFor+    :: (Reader Directory :> es)+    => Path.Relative+    -- ^ Path segment to append to runtime dir.+    -> (Path.Absolute -> a)+    -- ^ Constructor for the resulting type.+    -> Eff (Reader a : es) b+    -> Eff es b+asReaderFor path mk act = do+    Directory dir <- Reader.ask+    Reader.runReader (mk $ dir </> path) act
+ src/Tricorder/Runtime/LogPath.hs view
@@ -0,0 +1,40 @@+module Tricorder.Runtime.LogPath+    ( LogPath (..)+    , envName+    , asReader+    )+where++import Atelier.Effects.Env (Env)+import Atelier.FileSystem.Path ((</>))+import Data.Aeson (ToJSON)+import Effectful.Reader.Static (Reader)++import Atelier.Effects.Env qualified as Env+import Atelier.FileSystem.Path qualified as Path+import Effectful.Reader.Static qualified as Reader++import Tricorder.Runtime.Cache (Cache (..))++import Tricorder.Runtime.Cache qualified as Runtime (Cache)+++newtype LogPath = LogPath {getLogPath :: Path.Absolute}+    deriving stock (Eq, Generic, Show)+    deriving (ToJSON) via Path.Absolute+++envName :: String+envName = "TRICORDER_LOG_PATH"+++asReader :: (Env :> es, Reader Runtime.Cache :> es) => Eff (Reader LogPath : es) a -> Eff es a+asReader act = do+    mLogPath <- Env.lookup envName+    case mLogPath of+        Just logPath+            | Right path <- Path.fromFilePath logPath ->+                Reader.runReader (LogPath path) act+        _ -> do+            Cache cacheDir <- Reader.ask+            Reader.runReader (LogPath $ cacheDir </> Path.rel @"daemon.log") act
+ src/Tricorder/Runtime/PidFile.hs view
@@ -0,0 +1,17 @@+module Tricorder.Runtime.PidFile+    ( PidFile (..)+    , asReader+    )+where++import Atelier.Effects.Posix.Daemons (PidFile (..))+import Effectful.Reader.Static (Reader)++import Atelier.FileSystem.Path qualified as Path++import Tricorder.Runtime.Directory qualified as Runtime (Directory)+import Tricorder.Runtime.Directory qualified as Runtime.Directory+++asReader :: (Reader Runtime.Directory :> es) => Eff (Reader PidFile : es) a -> Eff es a+asReader = Runtime.Directory.asReaderFor (Path.relative @"daemon.pid") PidFile
+ src/Tricorder/Runtime/ProjectHash.hs view
@@ -0,0 +1,40 @@+module Tricorder.Runtime.ProjectHash+    ( ProjectHash (..)+    , asReader+    )+where++import Data.Aeson (FromJSON, ToJSON)+import Effectful.FileSystem (FileSystem)+import Effectful.Reader.Static (Reader)+import Numeric (showHex)++import Atelier.FileSystem.Path qualified as Path+import Atelier.FileSystem.Path.Internal qualified as Path.Internal+import Effectful.Reader.Static qualified as Reader++import Tricorder.Runtime.ProjectRoot (ProjectRoot (..))+++newtype ProjectHash = ProjectHash+    { getProjectHash :: Path.Relative+    }+    deriving stock (Eq, Generic, Show)+    deriving (FromJSON, ToJSON) via Path.Relative+++asReader+    :: (FileSystem :> es, Reader ProjectRoot :> es)+    => Eff (Reader ProjectHash : es) a -> Eff es a+asReader act = do+    ProjectRoot projectRoot <- Reader.ask+    canonProjectRoot <- Path.canonicalize projectRoot+    let hash = Path.Internal.UnsafeMkRelative $ hashPath $ Path.toFilePath canonProjectRoot+    Reader.runReader (ProjectHash hash) act+++-- | Polynomial hash of a file path, returned as a hex string.+hashPath :: FilePath -> String+hashPath path =+    let n = foldl' (\acc c -> acc * 31 + toInteger (ord c)) (0 :: Integer) path+    in  showHex (abs n `mod` (16 ^ (16 :: Integer))) ""
+ src/Tricorder/Runtime/ProjectRoot.hs view
@@ -0,0 +1,74 @@+module Tricorder.Runtime.ProjectRoot+    ( ProjectRoot (..)+    , asReader+    , findProjectRoot+    , findFileUpwards+    )+where++import Atelier.FileSystem.Path ((</>))+import Data.Aeson (ToJSON)+import Effectful.FileSystem (FileSystem)+import Effectful.Reader.Static (Reader, runReader)++import Atelier.FileSystem.Directory qualified as Directory+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path+++newtype ProjectRoot = ProjectRoot {getProjectRoot :: Path.Absolute}+    deriving stock (Eq)+    deriving (ToJSON) via Path.Absolute+++asReader+    :: (FileSystem :> es, HasCallStack)+    => Eff (Reader ProjectRoot : es) a -> Eff es a+asReader act = do+    cwd <- Directory.getCurrent+    projectRoot <- fromMaybe cwd <$> findProjectRoot cwd+    runReader (ProjectRoot projectRoot) act+++-- | Find the project root: the nearest directory, starting at the given one+-- and walking upwards, that contains a Stack or Cabal file.+--+-- This deliberately stops at a package directory even when it is part of a+-- larger multi-package project, so Tricorder can be used on one package at a+-- time. Use 'findFileUpwards' to locate project-level configuration such as+-- @stack.yaml@ or @cabal.project@ further up.+findProjectRoot :: (FileSystem :> es) => Path.Absolute -> Eff es (Maybe Path.Absolute)+findProjectRoot dir = do+    files <- Directory.list dir+    if+        | any isRootMarker files -> pure $ Just dir+        | parent == dir -> pure Nothing+        | otherwise -> findProjectRoot parent+  where+    parent = Path.takeDirectory dir+++-- | Find the nearest directory, starting at the given one and walking+-- upwards, that contains a file with the given name. This is how @stack@+-- looks for @stack.yaml@ and @cabal@ for @cabal.project@.+findFileUpwards+    :: (FileSystem :> es) => Path.Relative -> Path.Absolute -> Eff es (Maybe Path.Absolute)+findFileUpwards name dir = do+    found <- File.exists $ dir </> name+    if+        | found -> pure $ Just dir+        | parent == dir -> pure Nothing+        | otherwise -> findFileUpwards name parent+  where+    parent = Path.takeDirectory dir+++isRootMarker :: Path.Relative -> Bool+isRootMarker f =+    Path.takeExtension f == ".cabal"+        || Path.toFilePath f+            `elem` [ "cabal.project"+                   , "cabal.project.freeze"+                   , "cabal.project.local"+                   , "stack.yaml"+                   ]
+ src/Tricorder/Runtime/SocketPath.hs view
@@ -0,0 +1,25 @@+module Tricorder.Runtime.SocketPath+    ( SocketPath (..)+    , asReader+    )+where++import Data.Aeson (ToJSON)+import Effectful.Reader.Static (Reader)++import Atelier.FileSystem.Path qualified as Path++import Tricorder.Runtime.Directory qualified as Runtime (Directory)+import Tricorder.Runtime.Directory qualified as Runtime.Directory+++newtype SocketPath = SocketPath {getSocketPath :: Path.Absolute}+    deriving stock (Eq, Generic, Show)+    deriving (ToJSON) via Path.Absolute+++asReader+    :: (Reader Runtime.Directory :> es)+    => Eff (Reader SocketPath : es) a+    -> Eff es a+asReader = Runtime.Directory.asReaderFor (Path.relative @"socket.sock") SocketPath
src/Tricorder/Session.hs view
@@ -5,10 +5,12 @@     ) where -import Atelier.Effects.FileSystem (FileSystem) import Atelier.Effects.Input (Input) import Atelier.Effects.Log (Log)+import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (ToJSON) import Data.Default (Default (..))+import Effectful.FileSystem (FileSystem) import Effectful.Reader.Static (Reader) import Text.Regex.TDFA.Pattern (showPattern) @@ -17,7 +19,7 @@ import Data.Text qualified as T import Effectful.Reader.Static qualified as Reader -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot) import Tricorder.Session.CabalFile (CabalFile) import Tricorder.Session.CommandConfig (CommandConfig (..)) import Tricorder.Session.CommandTemplate (hasPlaceholder, targetPlaceholder)@@ -46,6 +48,7 @@ import Tricorder.Session.Stage.Test.Session qualified as Test (Session) import Tricorder.Session.Stage.Test.Session qualified as Test.Session import Tricorder.Session.WatchDirs qualified as WatchDirs+import Tricorder.Session.WatchExclusionPatterns qualified as WatchExclusionPatterns   data Session = Session@@ -59,7 +62,8 @@     , hooks :: Hooks     , idleTimeout :: IdleTimeout     }-    deriving stock (Eq)+    deriving stock (Eq, Generic)+    deriving (ToJSON) via QuietSnake Session   instance Default Session where@@ -92,12 +96,12 @@         Left err -> do             Log.err $ "Failed to parse config: " <> err             pure $ Left $ "Failed to parse Tricorder config: " <> err-        Right (Tricorder.Config cfgFile) -> Right <$> mkSession (fromMaybe def cfgFile)+        Right (Tricorder.Config cfgFile) -> mkSession (fromMaybe def cfgFile)   mkSession     :: (FileSystem :> es, Input [CabalFile] :> es, Log :> es, Reader ProjectRoot :> es)-    => Config -> Eff es Session+    => Config -> Eff es (Either Text Session) mkSession cfgFile = do     projectRoot <- Reader.ask @ProjectRoot     projectFiles <- Input.input@@ -122,38 +126,42 @@     testSession <- Test.Session.resolve repl buildSession.targets cfgFile     let evalSession = Eval.Session.resolve repl cfgFile         effectiveTargets = buildSession.targets <> (getTestTarget <$> testSession.targets)-        watchDirs = WatchDirs.resolve projectRoot projectFiles cfgFile effectiveTargets -    when (not (null effectiveTargets) && all (definesCustomPrelude projectFiles) effectiveTargets)-        $ Log.warn-            "Every resolved target exposes a custom Prelude module. GHCi may \-            \fail to start because the first target's Prelude will be loaded \-            \before its package is ready. Consider adding a target that does \-            \not define its own Prelude, or set an explicit command in your \-            \tricorder configuration."+    case WatchDirs.resolve projectRoot projectFiles cfgFile effectiveTargets of+        Left err ->+            pure $ Left $ "Failed to resolve watch dirs: " <> err+        Right watchDirs -> do+            when (not (null effectiveTargets) && all (definesCustomPrelude projectFiles) effectiveTargets)+                $ Log.warn+                    "Every resolved target exposes a custom Prelude module. GHCi may \+                    \fail to start because the first target's Prelude will be loaded \+                    \before its package is ready. Consider adding a target that does \+                    \not define its own Prelude, or set an explicit command in your \+                    \tricorder configuration." -    warnMissingTargetPlaceholder "test" cfgFile.test.commandConfig.commandTemplate-    warnMissingTargetPlaceholder "eval" cfgFile.eval.commandTemplate+            warnMissingTargetPlaceholder "test" cfgFile.test.commandConfig.commandTemplate+            warnMissingTargetPlaceholder "eval" cfgFile.eval.commandTemplate -    warnIgnoredextraAutoArguments "build" cfgFile.build.commandTemplate cfgFile.build.extraAutoArguments-    warnIgnoredextraAutoArguments-        "test"-        cfgFile.test.commandConfig.commandTemplate-        cfgFile.test.commandConfig.extraAutoArguments-    warnIgnoredextraAutoArguments "eval" cfgFile.eval.commandTemplate cfgFile.eval.extraAutoArguments+            warnIgnoredextraAutoArguments "build" cfgFile.build.commandTemplate cfgFile.build.extraAutoArguments+            warnIgnoredextraAutoArguments+                "test"+                cfgFile.test.commandConfig.commandTemplate+                cfgFile.test.commandConfig.extraAutoArguments+            warnIgnoredextraAutoArguments "eval" cfgFile.eval.commandTemplate cfgFile.eval.extraAutoArguments -    pure-        $ Session-            { buildSession-            , testSession-            , evalSession-            , watchDirs-            , watchExclusionPatterns-            , replBuildDir = ReplBuildDir cfgFile.replBuildDir-            , generateWithHpack = GenerateWithHpack cfgFile.generateWithHpack-            , hooks = fromMaybe def cfgFile.hooks-            , idleTimeout = IdleTimeout $ fromIntegral cfgFile.idleTimeoutSeconds-            }+            pure+                $ Right+                $ Session+                    { buildSession+                    , testSession+                    , evalSession+                    , watchDirs+                    , watchExclusionPatterns+                    , replBuildDir = ReplBuildDir cfgFile.replBuildDir+                    , generateWithHpack = GenerateWithHpack cfgFile.generateWithHpack+                    , hooks = fromMaybe def cfgFile.hooks+                    , idleTimeout = IdleTimeout $ fromIntegral cfgFile.idleTimeoutSeconds+                    }   -- | Warn once per session load for each deprecated top-level config key@@ -209,8 +217,7 @@ display session =     T.intercalate         "\n"-        [ "Loaded session"-        , "Build configuration:"+        [ "Build configuration:"         , indent $ Build.Session.display session.buildSession         , "Test configuration:"         , indent $ Test.Session.display session.testSession@@ -221,7 +228,7 @@         , "Watch exclusion patterns:"         , indent             $ displayList-                (toText . showPattern . fst)+                (toText . showPattern . fst . WatchExclusionPatterns.getPattern)                 session.watchExclusionPatterns.getWatchExclusionPatterns         , "Repl build dir: " <> toText session.replBuildDir.getReplBuildDir         , "Generate with hpack: " <> show session.generateWithHpack.getGenerateWithHpack
src/Tricorder/Session/CabalFile.hs view
@@ -8,44 +8,42 @@     ) where -import Atelier.Effects.Env (Env)-import Atelier.Effects.FileSystem (FileSystem, doesFileExist, listDirectory, readFileBs) import Atelier.Effects.FileSystem.Glob (Glob, globDir1) import Atelier.Effects.Input (Input) import Atelier.Effects.Log (Log)+import Atelier.FileSystem.Path (Path, (</>)) import Data.Traversable (for) import Distribution.Fields (Field (..), FieldLine (..), Name (..), readFields) import Distribution.PackageDescription.Parsec (parseGenericPackageDescriptionMaybe) import Distribution.Types.GenericPackageDescription (GenericPackageDescription) import Effectful.Exception (catch, throwIO)+import Effectful.FileSystem (FileSystem) import Effectful.Reader.Static (Reader)-import System.FilePath (normalise, takeExtension, (</>)) import System.FilePath.Glob (compile) import System.IO.Error (userError) -import Atelier.Effects.Env qualified as Env-import Atelier.Effects.FileSystem qualified as FileSystem import Atelier.Effects.Input qualified as Input import Atelier.Effects.Log qualified as Log+import Atelier.FileSystem.Directory qualified as Directory+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path import Data.ByteString.Char8 qualified as BC-import Data.List qualified as List import Data.Text qualified as T import Effectful.Reader.Static qualified as Reader -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.StackProject (StackProject (..))   data CabalFile = CabalFile-    { projectFilePath :: FilePath+    { projectFilePath :: Path.Absolute     , projectPackageDescription :: GenericPackageDescription     }     deriving stock (Show)   inputCabalFiles-    :: ( Env :> es-       , FileSystem :> es+    :: ( FileSystem :> es        , Glob :> es        , Input StackProject :> es        , Log :> es@@ -63,7 +61,7 @@             unless (null faileds) do                 Log.warn                     $ "Failed to parse .cabal files for the following packages: "-                        <> T.intercalate ", " (toText <$> faileds)+                        <> T.intercalate ", " (toText . Path.toFilePath <$> faileds)             pure $ packageDescriptions   where     logFailure =@@ -77,17 +75,17 @@  readProjectFile     :: (FileSystem :> es)-    => FilePath -> Eff es (Either FilePath CabalFile)+    => Path.Absolute -> Eff es (Either Path.Absolute CabalFile) readProjectFile projectFilePath = do-    fileExists <- FileSystem.doesFileExist projectFilePath+    fileExists <- File.exists projectFilePath     if fileExists         then readFile projectFilePath         else do-            dirExists <- FileSystem.doesDirectoryExist projectFilePath+            dirExists <- Directory.exists projectFilePath             if dirExists                 then do-                    files <- FileSystem.listDirectory projectFilePath-                    let mCabalFile = find (".cabal" `List.isSuffixOf`) files+                    files <- Directory.list projectFilePath+                    let mCabalFile = find (Path.relative @".cabal" `Path.isSuffixOf`) files                     case mCabalFile of                         Nothing -> pure $ Left projectFilePath                         Just cabalFile -> readFile $ projectFilePath </> cabalFile@@ -95,49 +93,52 @@                     pure $ Left projectFilePath   where     readFile path = do-        contents <- readFileBs path+        contents <- File.read path         case parseGenericPackageDescriptionMaybe contents of             Nothing -> pure $ Left path             Just gpd -> pure $ Right $ CabalFile path gpd   discoverPackages-    :: ( Env :> es-       , FileSystem :> es+    :: ( FileSystem :> es        , Glob :> es        , Input StackProject :> es        , Reader ProjectRoot :> es        )-    => Eff es (Either Text [FilePath])+    => Eff es (Either Text [Path.Absolute]) discoverPackages = do     ProjectRoot projectRoot <- Reader.ask-    hasStackYaml <- FileSystem.doesFileExist $ projectRoot </> "stack.yaml"+    hasStackYaml <- File.exists $ projectRoot </> Path.relative @"stack.yaml"     if hasStackYaml         then discoverStackPackages         else discoverCabalPackages  --- | Discovers `.cabal` files in all locations and formats Cabal itself+-- | Discovers @.cabal@ files in all locations and formats Cabal itself -- supports. discoverCabalPackages-    :: ( Env :> es-       , FileSystem :> es+    :: ( FileSystem :> es        , Glob :> es        , Reader ProjectRoot :> es        )-    => Eff es (Either Text [FilePath])+    => Eff es (Either Text [Path.Absolute]) discoverCabalPackages = do     ProjectRoot projectRoot <- Reader.ask-    homeCabalFiles <- maybe [] (one . (</> ".cabal/config")) <$> Env.lookup "HOME"+    homeCabalFiles <-+        Directory.getHome <&> \h ->+            (h </>)+                <$> [ Path.relative @".cabal/config"+                    , Path.relative @".config/cabal/config"+                    ]     let projectFilePaths = projectCabalFiles projectRoot <> homeCabalFiles-    projectFiles <- filterM doesFileExist projectFilePaths+    projectFiles <- filterM File.exists projectFilePaths     if null projectFiles         then             Right <$> cabalFilesIn projectRoot         else do             packages <- fmap (find (not . null))                 $ for projectFiles \projectFile -> do-                    contents <- readFileBs projectFile+                    contents <- File.read projectFile                     concat                         <$> traverse                             (cabalFilesForEntry projectRoot)@@ -147,48 +148,52 @@                 Just pkgs -> pure $ Right pkgs   where     projectCabalFiles projectRoot =-        (projectRoot </>) <$> ["cabal.project.local", "cabal.project.freeze", "cabal.project"]+        (projectRoot </>)+            <$> [ Path.relative @"cabal.project.local"+                , Path.relative @"cabal.project.freeze"+                , Path.relative @"cabal.project"+                ] -    cabalFilesForEntry projectRoot entry+    cabalFilesForEntry projectRoot (entry :: Path.Relative)         | hasWildcard entry = do-            matches <- globDir1 (compile entry) projectRoot+            matches <- globDir1 (compile $ Path.toFilePath entry) projectRoot             concat <$> traverse resolveMatch matches         | isCabalFile entry = pure [projectRoot </> entry]-        | otherwise = cabalFilesIn $ normalise $ projectRoot </> entry+        | otherwise = cabalFilesIn $ Path.normalise $ projectRoot </> entry       where         resolveMatch path-            | isCabalFile path = pure [path]-            | otherwise = cabalFilesIn path+            | isCabalFile path = pure [Path.normalise path]+            | otherwise = cabalFilesIn (Path.normalise path)   discoverStackPackages     :: (Input StackProject :> es, Reader ProjectRoot :> es)-    => Eff es (Either Text [FilePath])+    => Eff es (Either Text [Path.Absolute]) discoverStackPackages = do     ProjectRoot projectRoot <- Reader.ask     project <- Input.input-    pure $ Right $ normalise . (projectRoot </>) <$> project.packages+    pure $ Right $ Path.normalise . (projectRoot </>) <$> project.packages   -- | List the @.cabal@ files directly inside a directory.-cabalFilesIn :: (FileSystem :> es) => FilePath -> Eff es [FilePath]+cabalFilesIn :: (FileSystem :> es) => Path.Absolute -> Eff es [Path.Absolute] cabalFilesIn dir = do-    entries <- filter isCabalFile <$> listDirectory dir+    entries <- filter isCabalFile <$> Directory.list dir     pure $ (dir </>) <$> entries   -- | Does a @packages:@ entry contain a glob wildcard?-hasWildcard :: FilePath -> Bool-hasWildcard = elem '*'+hasWildcard :: (Path path) => path -> Bool+hasWildcard = elem '*' . Path.toFilePath   -- | Extract the directory/file entries from the @packages:@ field of a -- @cabal.project@.-projectPackageEntries :: ByteString -> [FilePath]+projectPackageEntries :: ByteString -> [Path.Relative] projectPackageEntries contents =     case readFields contents of         Left _ -> []-        Right fields -> concatMap fromField fields+        Right fields -> concatMap (mkPaths . fromField) fields   where     fromField = \case         (Field (Name _ name) fieldLines)@@ -200,7 +205,8 @@      dropComma ',' = ' '     dropComma c = c+    mkPaths = mapMaybe $ rightToMaybe . Path.fromFilePath @Path.Relative  -isCabalFile :: FilePath -> Bool-isCabalFile = (== ".cabal") . takeExtension+isCabalFile :: (Path path) => path -> Bool+isCabalFile = (== ".cabal") . Path.takeExtension
src/Tricorder/Session/CommandTemplate.hs view
@@ -9,6 +9,8 @@     ) where +import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (ToJSON) import Data.Default (Default (..))  import Data.List qualified as List@@ -32,6 +34,7 @@     -- see 'targetsPlaceholder' and 'targetPlaceholder'.     }     deriving stock (Eq, Generic, Show)+    deriving (ToJSON) via QuietSnake (CommandTemplate stage)   -- | The @{targets}@ placeholder, used by @build@: one invocation covers
src/Tricorder/Session/Hook.hs view
@@ -4,15 +4,19 @@     ) where +import Atelier.Effects.Log (Log) import Atelier.Effects.Process (Process) import Data.Aeson (FromJSON, ToJSON) import Effectful.Exception (trySync) import Effectful.Reader.Static (Reader)+import System.Exit (ExitCode (..)) +import Atelier.Effects.Log qualified as Log import Atelier.Effects.Process qualified as Process+import Data.Text qualified as T import Effectful.Reader.Static qualified as Reader -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..))   newtype Hook = Hook {getHook :: Text}@@ -20,12 +24,43 @@     deriving (FromJSON, ToJSON) via Text  -run :: (Process :> es, Reader ProjectRoot :> es) => Hook -> Eff es ()+run :: (Log :> es, Process :> es, Reader ProjectRoot :> es) => Hook -> Eff es () run (Hook hook) = do     ProjectRoot root <- Reader.ask-    void-        $ trySync-        $ Process.runProcess-        $ Process.setWorkingDir root-        $ Process.shell-        $ toString hook+    Log.debug $ "Running hook: " <> hook+    res <-+        trySync+            $ Process.readProcess+            $ Process.setWorkingDir root+            $ Process.shell+            $ toString hook+    case res of+        Left err ->+            Log.warn $ "Hook failed to run: " <> toText (displayException err)+        Right (ExitFailure code, stdout, stderr) -> do+            let+                displayError kind e =+                    mconcat+                        [ "Unable to decode "+                        , kind+                        , ": "+                        , toText (displayException e)+                        ]+                decode kind =+                    either (displayError kind) (("Hook " <> kind <> " output: ") <>)+                        . decodeUtf8Strict+                        . toStrict+            Log.warn+                $ T.intercalate+                    "\n"+                    [ "Hook exited with a non-zero exit code: " <> show code+                    , "Hook output emitted as DEBUG logs."+                    ]+            Log.debug+                $ T.intercalate+                    "\n"+                    [ decode "stdout" stdout+                    , decode "stderr" stderr+                    ]+        Right (ExitSuccess, _, _) ->+            pure ()
src/Tricorder/Session/Repl.hs view
@@ -4,21 +4,25 @@     ) where -import Atelier.Effects.FileSystem (FileSystem)+import Atelier.FileSystem.Path ((</>))+import Data.Aeson (ToJSON) import Data.Yaml (decodeEither') import Effectful.Exception (throwIO)-import System.FilePath ((</>))+import Effectful.FileSystem (FileSystem)+import GHC.Generics (Generically (..)) import System.IO.Error (userError) -import Atelier.Effects.FileSystem qualified as FileSystem+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path import Data.Aeson qualified as Aeson import Data.Aeson.KeyMap qualified as KM -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..), findFileUpwards)   data Repl = StackMulti | Stack | Cabal | Unknown     deriving stock (Eq, Generic, Show)+    deriving (ToJSON) via Generically Repl   -- | Resolve the project's REPL kind from the filesystem, independent of any@@ -26,16 +30,18 @@ -- automatically resolved templates and how targets are rendered for all -- three phases. resolveRepl :: (FileSystem :> es) => ProjectRoot -> Eff es Repl-resolveRepl pr@(ProjectRoot projectRoot) = do-    hasStack <- FileSystem.doesFileExist $ projectRoot </> "stack.yaml"-    if hasStack-        then stackReplKind pr-        else pure Cabal+resolveRepl (ProjectRoot projectRoot) = do+    stackDir <- findFileUpwards stackYaml projectRoot+    case stackDir of+        Just dir -> stackReplKind $ dir </> stackYaml+        Nothing -> pure Cabal+  where+    stackYaml = Path.rel @"stack.yaml"  -stackReplKind :: (FileSystem :> es) => ProjectRoot -> Eff es Repl-stackReplKind (ProjectRoot projectRoot) = do-    stackYaml <- FileSystem.readFileBs $ projectRoot </> "stack.yaml"+stackReplKind :: (FileSystem :> es) => Path.Absolute -> Eff es Repl+stackReplKind stackYamlPath = do+    stackYaml <- File.read stackYamlPath     case decodeEither' stackYaml of         Left err -> throwIO $ userError $ "Could not read and decode stack.yaml: " <> show err         Right value -> pure $ case value of
src/Tricorder/Session/StackProject.hs view
@@ -4,39 +4,41 @@     ) where -import Atelier.Effects.FileSystem (FileSystem) import Atelier.Effects.Input (Input)-import Data.Aeson (FromJSON, ToJSON)+import Atelier.FileSystem.Path ((</>))+import Data.Aeson (FromJSON (..), ToJSON, (.!=), (.:?)) import Data.Time (UTCTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Effectful.Concurrent.MVar.Strict (Concurrent)-import Effectful.Concurrent.STM-    ( TVar-    , atomically-    , newTVarIO-    , readTVar-    , writeTVar-    )+import Effectful.Concurrent.STM (TVar, atomically, newTVarIO, readTVar, writeTVar) import Effectful.Exception (throwIO)+import Effectful.FileSystem (FileSystem) import Effectful.Reader.Static (Reader, ask) import GHC.Generics (Generically (..))-import System.FilePath ((</>)) import System.IO.Error (userError) -import Atelier.Effects.FileSystem qualified as FileSystem import Atelier.Effects.Input qualified as Input+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path+import Data.Aeson qualified as Aeson import Data.Yaml qualified as Yaml -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..))   newtype StackProject = StackProject-    { packages :: [FilePath]+    { packages :: [Path.Relative]     }     deriving stock (Eq, Generic, Show)-    deriving (FromJSON, ToJSON) via Generically StackProject+    deriving (ToJSON) via Generically StackProject  +-- | Stack defaults @packages@ to @["."]@ when the field is absent.+instance FromJSON StackProject where+    parseJSON = Aeson.withObject "StackProject" \o ->+        StackProject <$> o .:? "packages" .!= [Path.rel @"."]++ inputWithCache     :: ( Concurrent :> es        , FileSystem :> es@@ -48,16 +50,16 @@     lastModified :: TVar UTCTime <- newTVarIO $ posixSecondsToUTCTime 0     flip Input.withEff act do         ProjectRoot projectRoot <- ask-        let stackYamlPath = projectRoot </> "stack.yaml"-        exists <- FileSystem.doesFileExist stackYamlPath+        let stackYamlPath = projectRoot </> Path.relative @"stack.yaml"+        exists <- File.exists stackYamlPath         if not exists             then throwIO $ userError "stack.yaml does not exist"             else do-                newLastMod <- FileSystem.getModificationTime stackYamlPath+                newLastMod <- File.getModificationTime stackYamlPath                 oldLastMod <- atomically $ readTVar lastModified                 if oldLastMod /= newLastMod                     then do-                        contents <- FileSystem.readFileBs stackYamlPath+                        contents <- File.read stackYamlPath                         let result = Yaml.decodeEither' contents                         case result of                             Right x -> do
src/Tricorder/Session/Stage/Build/Command.hs view
@@ -4,13 +4,12 @@     ) where -import Atelier.Effects.FileSystem (FileSystem)-import System.FilePath ((</>))+import Effectful.FileSystem (FileSystem) -import Atelier.Effects.FileSystem qualified as FileSystem-import Data.List qualified as List+import Atelier.FileSystem.Directory qualified as Directory+import Atelier.FileSystem.Path qualified as Path -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..), findFileUpwards) import Tricorder.Session.Command.RenderedCommand (RenderedCommand (..)) import Tricorder.Session.CommandConfig (CommandConfig (..)) import Tricorder.Session.CommandTemplate (CommandTemplate (..), renderText, targetsPlaceholder)@@ -55,9 +54,11 @@ -- bearing on 'Repl', which is 'Cabal' either way. isCabalProject :: (FileSystem :> es) => ProjectRoot -> Eff es Bool isCabalProject (ProjectRoot projectRoot) = do-    hasCabalProject <- FileSystem.doesFileExist $ projectRoot </> "cabal.project"-    hasCabalFiles <- any (".cabal" `List.isSuffixOf`) <$> FileSystem.listDirectory projectRoot+    hasCabalProject <- isJust <$> findFileUpwards cabalProject projectRoot+    hasCabalFiles <- any (Path.rel @".cabal" `Path.isSuffixOf`) <$> Directory.list projectRoot     pure $ hasCabalProject || hasCabalFiles+  where+    cabalProject = Path.rel @"cabal.project"   -- | Tricorder's automatically resolved @build@ template for a resolved
src/Tricorder/Session/Stage/Build/Session.hs view
@@ -5,18 +5,18 @@     ) where -import Atelier.Effects.FileSystem (FileSystem)+import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (ToJSON) import Data.Default (Default (..))+import Effectful.FileSystem (FileSystem) import Effectful.Reader.Static (Reader)  import Data.Text qualified as T import Effectful.Reader.Static qualified as Reader -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot) import Tricorder.Session.CabalFile (CabalFile)-import Tricorder.Session.CommandConfig-    ( CommandConfig (..)-    )+import Tricorder.Session.CommandConfig (CommandConfig (..)) import Tricorder.Session.CommandTemplate (CommandTemplate) import Tricorder.Session.Config (Config (..)) import Tricorder.Session.Repl (Repl)@@ -37,7 +37,8 @@     , targets :: [Target]     , ghci :: Ghci.Config     }-    deriving stock (Eq)+    deriving stock (Eq, Generic)+    deriving (ToJSON) via QuietSnake Session   instance Default Session where
src/Tricorder/Session/Stage/Eval/Session.hs view
@@ -5,6 +5,10 @@     ) where +import Atelier.Types.JSON.QuietSnake+    ( QuietSnake (..)+    )+import Data.Aeson (ToJSON) import Data.Default (Default (..))  import Data.Text qualified as T@@ -27,7 +31,8 @@     { commandTemplate :: CommandTemplate 'Stage.Eval     , ghci :: Ghci.Config     }-    deriving stock (Eq)+    deriving stock (Eq, Generic)+    deriving (ToJSON) via QuietSnake Session   instance Default Session where
src/Tricorder/Session/Stage/Test/Session.hs view
@@ -8,11 +8,12 @@ where  import Atelier.Effects.Log (Log)-import Atelier.Time (Millisecond)+import Atelier.Time (AsRawUnit (..), Millisecond)+import Atelier.Types.JSON.QuietSnake (QuietSnake (..))+import Data.Aeson (ToJSON) import Data.Default (Default (..))  import Atelier.Effects.Log qualified as Log-import Atelier.Time qualified as Time import Data.Text qualified as T  import Tricorder.Build.ByteSize (ByteSize)@@ -40,7 +41,8 @@     , options :: ResolvedTestOptions     , ghci :: Ghci.Config     }-    deriving stock (Eq)+    deriving stock (Eq, Generic)+    deriving (ToJSON) via QuietSnake Session   instance Default Session where@@ -55,17 +57,18 @@  data ResolvedTestOptions = ResolvedTestOptions     { outputMode :: OutputMode-    , timeout :: Millisecond+    , timeout :: AsRawUnit Millisecond     , memoryLimit :: Maybe ByteSize     }-    deriving stock (Eq)+    deriving stock (Eq, Generic)+    deriving (ToJSON) via QuietSnake ResolvedTestOptions   instance Default ResolvedTestOptions where     def =         ResolvedTestOptions             { outputMode = ReplOutput-            , timeout = 10+            , timeout = AsRawUnit 10             , memoryLimit = Nothing             } @@ -98,7 +101,7 @@             , options =                 ResolvedTestOptions                     { outputMode = fromMaybe detectedOutputMode cfg.test.options.outputMode-                    , timeout = maybe 10 Time.getAsRawUnit cfg.test.options.timeoutMs+                    , timeout = fromMaybe (AsRawUnit 10) cfg.test.options.timeoutMs                     , memoryLimit                     }             , ghci = maybe def Ghci.Config.File.toConfig cfg.test.commandConfig.ghci
src/Tricorder/Session/State.hs view
@@ -11,7 +11,6 @@ import Atelier.Effects.Clock (Clock) import Atelier.Effects.Conc (Conc) import Atelier.Effects.Debounce (Debounce)-import Atelier.Effects.FileSystem (FileSystem) import Atelier.Effects.FileWatcher (FileWatcher) import Atelier.Effects.Input (Input) import Atelier.Effects.Log (Log)@@ -20,12 +19,11 @@ import Effectful (Effect, Limit (..), Persistence (..), UnliftStrategy (..), inject) import Effectful.Concurrent.STM (Concurrent, TVar) import Effectful.Dispatch.Dynamic (interpretWith, localUnlift)+import Effectful.FileSystem (FileSystem) import Effectful.Reader.Static (Reader) import Effectful.TH (makeEffect)-import System.FilePath ((</>))  import Atelier.Effects.Conc qualified as Conc-import Atelier.Effects.FileSystem qualified as FileSystem import Atelier.Effects.FileWatcher qualified as FileWatcher import Atelier.Effects.FileWatcher.Watch qualified as Watch import Atelier.Effects.Input qualified as Input@@ -33,12 +31,12 @@ import Atelier.Effects.PubSub qualified as PubSub import Atelier.Effects.PubSub.Pub qualified as Pub import Atelier.Effects.PubSub.Sub qualified as Sub-import Data.List qualified as List+import Atelier.FileSystem.Path qualified as Path import Data.Text qualified as T import Effectful.Concurrent.STM qualified as STM import Effectful.Reader.Static qualified as Reader -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..), findFileUpwards) import Tricorder.Session.CabalFile (CabalFile) import Tricorder.Session.State.Invalid (Invalid (..)) import Tricorder.Session.State.Result (Result)@@ -137,7 +135,7 @@ watchConfigFile = do     root <- Reader.ask     FileWatcher.watchFilePathsDebounced-        [Watch.dirWhere root.getProjectRoot (LoadedConfig.configFileName `List.isSuffixOf`)]+        [Watch.dirWhere root.getProjectRoot (LoadedConfig.configFileName `Path.isSuffixOf`)]         \_ _ -> Pub.publish Reload  @@ -152,10 +150,13 @@     => Eff es () conditionallyWatchStackYaml = do     root <- Reader.ask-    exists <- FileSystem.doesFileExist $ root.getProjectRoot </> "stack.yaml"-    when exists do+    stackDir <- findFileUpwards (Path.rel @"stack.yaml") root.getProjectRoot+    for_ stackDir \dir ->         Conc.fork_ $ FileWatcher.watchFilePathsDebounced-            [Watch.dirWhere root.getProjectRoot ("stack.yaml" `List.isSuffixOf`)]+            [ Watch.dirWhere dir (Path.rel @"stack.yaml" `Path.isSuffixOf`)+                `Watch.excluding` Watch.containing ".stack-work"+                `Watch.excluding` Watch.containing "dist-newstyle"+            ]             \_ _ -> Pub.publish Reload  @@ -171,4 +172,4 @@                 , indent $ indent $ Session.display invalid.fallback                 ]     Result.Ok session ->-        Log.info . (<> "\n") $ Session.display session+        Log.info . (<> "\n") $ "Session:" <> Session.display session
src/Tricorder/Session/WatchDirs.hs view
@@ -6,6 +6,7 @@     ) where +import Atelier.FileSystem.Path ((</>)) import Data.Aeson (FromJSON (..), ToJSON (..)) import Data.Default (Default (..)) import Data.List (nub)@@ -26,20 +27,21 @@ import Distribution.Types.PackageName (unPackageName) import Distribution.Types.UnqualComponentName (mkUnqualComponentName) import Distribution.Utils.Path (getSymbolicPath)-import System.FilePath (takeDirectory, (</>)) +import Atelier.FileSystem.Path qualified as Path+import Data.List qualified as List import Data.Text qualified as T import Distribution.Types.BuildInfo.Lens qualified as Lens -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.CabalFile (CabalFile (..)) import Tricorder.Session.Config (Config (..)) import Tricorder.Session.Target (ComponentKind (..), Target (..))  -newtype WatchDirs = WatchDirs {getWatchDirs :: [FilePath]}+newtype WatchDirs = WatchDirs {getWatchDirs :: [Path.Absolute]}     deriving stock (Eq, Generic, Show)-    deriving (FromJSON, ToJSON) via [FilePath]+    deriving (FromJSON, ToJSON) via [Path.Absolute]   instance Default WatchDirs where@@ -48,69 +50,82 @@  -- | Resolve the directories to watch. --+-- Returns 'Left' if a configured or inferred directory is not a valid path.+-- -- Priority:--- 1. @watch_dirs@ from config, if non-empty (used as-is relative to project root)+-- 1. @watch_dirs@ from config, if non-empty (relative entries are resolved+--    against the project root; absolute entries are used as-is) -- 2. @hs-source-dirs@ inferred from cabal targets, if targets are set--- 3. Falls back to @["."]@ (project root) if neither is available-resolve :: ProjectRoot -> [CabalFile] -> Config -> [Target] -> WatchDirs-resolve projectRoot projectFiles cfg targets =-    case cfg.watchDirs of-        dirs@(_ : _) -> WatchDirs $ map (coerce projectRoot </>) dirs-        [] -> resolveWatchDirsFromTargets projectFiles targets+-- 3. Falls back to the project root if neither is available+resolve :: ProjectRoot -> [CabalFile] -> Config -> [Target] -> Either Text WatchDirs+resolve (ProjectRoot projectRoot) projectFiles cfg targets+    | List.null cfg.watchDirs = resolveWatchDirsFromTargets projectRoot projectFiles targets+    | otherwise =+        fmap+            ( WatchDirs . fmap \case+                Path.Absolute p -> p+                Path.Relative p -> projectRoot </> p+            )+            $ traverse Path.fromFilePath cfg.watchDirs  -resolveWatchDirsFromTargets :: [CabalFile] -> [Target] -> WatchDirs-resolveWatchDirsFromTargets _ [] = WatchDirs ["."]-resolveWatchDirsFromTargets projectFiles targets =-    WatchDirs $ case dirs of-        [] -> ["."]-        _ -> dirs+resolveWatchDirsFromTargets :: Path.Absolute -> [CabalFile] -> [Target] -> Either Text WatchDirs+resolveWatchDirsFromTargets projectRoot _ [] = Right $ WatchDirs [projectRoot]+resolveWatchDirsFromTargets projectRoot projectFiles targets =+    case dirs of+        Left err -> Left $ "Could not resolve watch dirs from target: " <> err+        Right [] -> Right $ WatchDirs [projectRoot]+        Right ds -> Right $ WatchDirs ds   where-    dirs = nub . concat $ watchDirsForCabal <$> projectFiles+    dirs = nub . concat <$> traverse watchDirsForCabal projectFiles     -- @hs-source-dirs@ are relative to the package's own directory, so scope     -- them to the directory holding that package's @.cabal@. In a     -- single-package project that directory is the project root; in a     -- multi-package project it's the per-package subdirectory. Targets that     -- don't belong to this package yield no dirs.     watchDirsForCabal projectFile =-        let pkgDir = takeDirectory projectFile.projectFilePath+        let pkgDir = Path.takeDirectory projectFile.projectFilePath             sourceDirs = sourceDirsForTarget projectFile.projectPackageDescription-        in  (pkgDir </>) <$> concatMap sourceDirs targets+            absIfy = \case+                Path.Absolute p -> p+                Path.Relative p -> pkgDir </> p+        in  concat . fmap (fmap absIfy) <$> traverse sourceDirs targets  -sourceDirsForTarget :: GenericPackageDescription -> Target -> [FilePath]+sourceDirsForTarget :: GenericPackageDescription -> Target -> Either Text [Path.Any] sourceDirsForTarget gpd target =-    map getSymbolicPath $ case target of-        Qualified Lib "" -> mainLibSourceDirs-        Qualified Lib name-            | toString name == mainPkgName -> mainLibSourceDirs-            | otherwise -> subLibSourceDirs name-        Qualified FLib name -> flibSourceDirs name-        Qualified Exe name -> exeSourceDirs name-        Qualified Test name -> testSourceDirs name-        Qualified Bench name -> benchSourceDirs name-        PackageQualified _ Lib "" -> mainLibSourceDirs-        PackageQualified _ Lib name-            | toString name == mainPkgName -> mainLibSourceDirs-            | otherwise -> subLibSourceDirs name-        PackageQualified _ FLib name -> flibSourceDirs name-        PackageQualified _ Exe name -> exeSourceDirs name-        PackageQualified _ Test name -> testSourceDirs name-        PackageQualified _ Bench name -> benchSourceDirs name-        -- A bare target (no @kind:@ prefix) is a package name or a component-        -- name. A package name covers every component; otherwise match a-        -- single component by name across the kinds.-        Bare name-            | toString name == mainPkgName -> allComponentSourceDirs-            | otherwise -> componentSourceDirsByName name-        -- [tag:alias_name_match] A form we couldn't parse into a kind — a cabal-        -- alias (@executable:@) or a case variant (@Lib:@). The kind is-        -- untrustworthy, but cabal component names are unique within a package,-        -- so we match the trailing name across every kind. This recovers precise-        -- watch dirs for aliased spellings; worst case we over-match a-        -- same-named component, never miss one. (The raw string is still handed-        -- to cabal verbatim for the build.)-        Unrecognized raw -> componentSourceDirsByName (T.takeWhileEnd (/= ':') raw)+    traverse Path.fromFilePath+        $ getSymbolicPath <$> case target of+            Qualified Lib "" -> mainLibSourceDirs+            Qualified Lib name+                | toString name == mainPkgName -> mainLibSourceDirs+                | otherwise -> subLibSourceDirs name+            Qualified FLib name -> flibSourceDirs name+            Qualified Exe name -> exeSourceDirs name+            Qualified Test name -> testSourceDirs name+            Qualified Bench name -> benchSourceDirs name+            PackageQualified _ Lib "" -> mainLibSourceDirs+            PackageQualified _ Lib name+                | toString name == mainPkgName -> mainLibSourceDirs+                | otherwise -> subLibSourceDirs name+            PackageQualified _ FLib name -> flibSourceDirs name+            PackageQualified _ Exe name -> exeSourceDirs name+            PackageQualified _ Test name -> testSourceDirs name+            PackageQualified _ Bench name -> benchSourceDirs name+            -- A bare target (no @kind:@ prefix) is a package name or a component+            -- name. A package name covers every component; otherwise match a+            -- single component by name across the kinds.+            Bare name+                | toString name == mainPkgName -> allComponentSourceDirs+                | otherwise -> componentSourceDirsByName name+            -- [tag:alias_name_match] A form we couldn't parse into a kind — a cabal+            -- alias (@executable:@) or a case variant (@Lib:@). The kind is+            -- untrustworthy, but cabal component names are unique within a package,+            -- so we match the trailing name across every kind. This recovers precise+            -- watch dirs for aliased spellings; worst case we over-match a+            -- same-named component, never miss one. (The raw string is still handed+            -- to cabal verbatim for the build.)+            Unrecognized raw -> componentSourceDirsByName (T.takeWhileEnd (/= ':') raw)   where     mainPkgName = unPackageName . pkgName . package . packageDescription $ gpd @@ -155,10 +170,10 @@   -- | The @hs-source-dirs@ of every component in the package, relative to the--- package's own directory.-allSourceDirs :: GenericPackageDescription -> [FilePath]+-- package's own directory (unless absolute). 'Left' if any is not a valid path.+allSourceDirs :: GenericPackageDescription -> Either Text [Path.Any] allSourceDirs gpd =-    nub+    fmap nub         . sourceDirsForTarget gpd         . Bare         . toText
src/Tricorder/Session/WatchExclusionPatterns.hs view
@@ -1,11 +1,13 @@ module Tricorder.Session.WatchExclusionPatterns     ( WatchExclusionPatterns (..)-    , Pattern+    , Pattern (..)     , resolveWatchExclusionPatterns     ) where +import Data.Aeson (ToJSON (..)) import Data.Default (Default (..))+import Text.Regex.TDFA.Pattern (showPattern) import Text.Regex.TDFA.ReadRegex (parseRegex)  import Text.Regex.TDFA.Pattern qualified as Regex@@ -13,16 +15,25 @@  newtype WatchExclusionPatterns = WatchExclusionPatterns {getWatchExclusionPatterns :: [Pattern]}     deriving stock (Eq, Generic, Show)+    deriving (ToJSON) via [Pattern]   instance Default WatchExclusionPatterns where     def = WatchExclusionPatterns []  -type Pattern = (Regex.Pattern, (Regex.GroupIndex, Regex.DoPa))+newtype Pattern = Pattern+    { getPattern :: (Regex.Pattern, (Regex.GroupIndex, Regex.DoPa))+    }+    deriving stock (Eq, Show)  +instance ToJSON Pattern where+    toJSON (Pattern (pat, _)) = toJSON $ showPattern pat+    toEncoding (Pattern (pat, _)) = toEncoding $ showPattern pat++ resolveWatchExclusionPatterns :: [Text] -> Either Text WatchExclusionPatterns resolveWatchExclusionPatterns rawPatterns = do     bimap show WatchExclusionPatterns-        $ traverse (parseRegex . toString) rawPatterns+        $ traverse (fmap Pattern . parseRegex . toString) rawPatterns
src/Tricorder/Socket/Client.hs view
@@ -11,8 +11,9 @@ where  import Atelier.Effects.Delay (Delay)-import Atelier.Effects.File (File, Handle)+import Atelier.Effects.Handles (Handle, Handles) import Atelier.Effects.Posix.Daemons (Daemons)+import Atelier.FileSystem.Path (Path) import Atelier.Time (Millisecond) import Data.Aeson (decode, eitherDecode, encode) import Effectful (inject)@@ -24,13 +25,12 @@ import Prelude hiding (force)  import Atelier.Effects.Delay qualified as Delay-import Atelier.Effects.File qualified as File+import Atelier.Effects.Handles qualified as Handles import Atelier.Effects.Posix.Daemons qualified as Daemons import Data.ByteString.Lazy qualified as BSL import Tricorder.API.IfThereArePendingQueries qualified as IfThereArePendingQueries -import Tricorder.Build (BuildState, Diagnostic)-import Tricorder.Runtime (PidFile)+import Tricorder.Runtime.PidFile (PidFile) import Tricorder.Socket.Protocol     ( ClientMessage (..)     , DiagnosticQuery (..)@@ -40,14 +40,16 @@     ) import Tricorder.Socket.UnixSocket (UnixSocket, withConnection) +import Tricorder.Build.Diagnostic qualified as Build (Diagnostic)+import Tricorder.Build.State qualified as Build (State) import Tricorder.Version qualified as Version   -- | Query the current build status (non-blocking). queryStatus-    :: (File :> es, UnixSocket :> es)-    => FilePath-    -> Eff es (Either Text BuildState)+    :: (Handles :> es, Path path, UnixSocket :> es)+    => path+    -> Eff es (Either Text Build.State) queryStatus sockPath = withConnection sockPath \h -> do     sendQuery h (Status (StatusQuery {awaitDone = False}))     receiveState h@@ -55,9 +57,9 @@  -- | Query the build status, blocking until the current build cycle completes. queryStatusWait-    :: (File :> es, UnixSocket :> es)-    => FilePath-    -> Eff es (Either Text BuildState)+    :: (Handles :> es, Path path, UnixSocket :> es)+    => path+    -> Eff es (Either Text Build.State) queryStatusWait sockPath = withConnection sockPath \h -> do     sendQuery h (Status (StatusQuery {awaitDone = True}))     receiveState h@@ -75,12 +77,12 @@ -- survives the gap between stopping the old daemon and the new one binding its -- socket. queryWatch-    :: forall es-     . (Delay :> es, File :> es, UnixSocket :> es)-    => FilePath+    :: forall path es+     . (Delay :> es, Handles :> es, Path path, UnixSocket :> es)+    => path     -> Eff es Bool     -- ^ Whether a restart is currently in progress.-    -> (Either Restarting BuildState -> Eff es ())+    -> (Either Restarting Build.State -> Eff es ())     -> Eff es () queryWatch sockPath isRestarting handler = evalState retryLimit retryLoop   where@@ -98,7 +100,7 @@         mLine <-             catchJust                 (\e -> if isEOFError e then Just e else Nothing)-                (Just <$> File.hGetLine h)+                (Just <$> Handles.hGetLine h)                 (\_ -> pure Nothing)         case mLine of             Nothing -> inject $ handler (Left Restarting)@@ -112,24 +114,24 @@  -- | Fetch the full body of a single diagnostic by 1-based index. queryDiagnostic-    :: (File :> es, UnixSocket :> es)-    => FilePath+    :: (Handles :> es, Path path, UnixSocket :> es)+    => path     -> Int-    -> Eff es (Either Text Diagnostic)+    -> Eff es (Either Text Build.Diagnostic) queryDiagnostic sockPath idx = withConnection sockPath \h -> do     sendQuery h (DiagnosticAt (DiagnosticQuery {index = idx}))-    line <- File.hGetLine h+    line <- Handles.hGetLine h     case eitherDecode (BSL.fromStrict (encodeUtf8 (toText line))) of         Left err -> pure $ Left (toText err)         Right d -> pure $ Right d   requestShutdown-    :: (File :> es, UnixSocket :> es)-    => IfThereArePendingQueries -> FilePath -> Eff es (Either Text ())+    :: (Handles :> es, Path path, UnixSocket :> es)+    => IfThereArePendingQueries -> path -> Eff es (Either Text ()) requestShutdown force sockPath = withConnection sockPath \h -> do     sendQuery h $ Quit waiters-    line <- File.hGetLine h+    line <- Handles.hGetLine h     if eitherDecode (BSL.fromStrict (encodeUtf8 line)) == Right True         then             pure $ Right ()@@ -153,7 +155,7 @@ -- running process is not enough to guarantee a client can connect. This opens -- (and immediately closes) a throwaway connection and reports whether it -- succeeded.-isDaemonReady :: (UnixSocket :> es) => FilePath -> Eff es Bool+isDaemonReady :: (Path path, UnixSocket :> es) => path -> Eff es Bool isDaemonReady sockPath =     either (const False) (const True)         <$> trySync (withConnection sockPath \_ -> pass)@@ -161,13 +163,13 @@  -- internals -sendQuery :: (File :> es) => Handle -> Query -> Eff es ()-sendQuery h q = File.hPutLBsLn h $ encode ClientMessage {clientVersion = Version.gitHash, payload = q}+sendQuery :: (Handles :> es) => Handle -> Query -> Eff es ()+sendQuery h q = Handles.hPutLBsLn h $ encode ClientMessage {clientVersion = Version.gitHash, payload = q}  -receiveState :: (File :> es) => Handle -> Eff es (Either Text BuildState)+receiveState :: (Handles :> es) => Handle -> Eff es (Either Text Build.State) receiveState h = do-    line <- File.hGetLine h+    line <- Handles.hGetLine h     case eitherDecode (BSL.fromStrict (encodeUtf8 (toText line))) of         Left err -> pure $ Left (toText err)         Right state -> pure $ Right state
src/Tricorder/Socket/Server.hs view
@@ -2,29 +2,30 @@  import Atelier.Effects.Conc (Conc) import Atelier.Effects.Exit (Exit)-import Atelier.Effects.File (File)-import Atelier.Effects.FileSystem (FileSystem)+import Atelier.Effects.Handles (Handles) import Atelier.Effects.Input (Input, input) import Atelier.Effects.Log (Log) import Atelier.Effects.PubSub.Sub (Sub) import Data.Aeson (ToJSON, decode, encode) import Effectful.Exception (IOException, finally, trySync)+import Effectful.FileSystem (FileSystem) import Effectful.Reader.Static (Reader, ask) import Effectful.State.Static.Shared (State) import System.IO (Handle)  import Atelier.Effects.Conc qualified as Conc import Atelier.Effects.Exit qualified as Exit-import Atelier.Effects.File qualified as File-import Atelier.Effects.FileSystem qualified as FileSystem+import Atelier.Effects.Handles qualified as Handles import Atelier.Effects.Log qualified as Log import Atelier.Effects.PubSub.Sub qualified as Sub+import Atelier.FileSystem.File qualified as File import Data.ByteString.Lazy qualified as BSL import Effectful.State.Static.Shared qualified as State -import Tricorder.Build (BuildId, BuildPhase, BuildState (..), Diagnostic)+import Tricorder.Build.PostBuild (PostBuild (..))+import Tricorder.Build.Result (Result (..)) import Tricorder.Daemon.IdleTimer (IdleTimer)-import Tricorder.Runtime (SocketPath (..))+import Tricorder.Runtime.SocketPath (SocketPath (..)) import Tricorder.Socket.Protocol     ( ClientMessage (..)     , DiagnosticQuery (..)@@ -36,8 +37,12 @@ import Tricorder.Version (VersionMismatch (..), checkVersion) import Tricorder.Waiters (Waiters) -import Tricorder.Build qualified as Build+import Tricorder.Build.Diagnostic qualified as Build (Diagnostic) import Tricorder.Build.EvalComment qualified as Eval+import Tricorder.Build.Id qualified as Build (Id)+import Tricorder.Build.Phase qualified as Build (Phase)+import Tricorder.Build.Phase qualified as Build.Phase+import Tricorder.Build.State qualified as Build (State (..)) import Tricorder.Build.Test qualified as Test import Tricorder.Daemon.IdleTimer qualified as IdleTimer import Tricorder.Socket.Protocol qualified as Protocol@@ -52,35 +57,35 @@ main     :: ( Conc :> es        , Exit :> es-       , File :> es        , FileSystem :> es+       , Handles :> es        , IdleTimer :> es-       , Input BuildId :> es+       , Input Build.Id :> es        , Log :> es        , Reader SocketPath :> es-       , Sub BuildPhase :> es+       , Sub Build.Phase :> es        , UnixSocket :> es        , Waiters :> es        )     => Eff es Void-main = State.evalState Build.Starting do-    Conc.fork_ $ Sub.listen_ @BuildPhase State.put+main = State.evalState Build.Phase.Starting do+    Conc.fork_ $ Sub.listen_ @Build.Phase State.put      SocketPath sockPath <- ask-    void $ trySync $ FileSystem.removeFile sockPath+    void $ trySync $ File.remove sockPath     acceptTrigger   acceptTrigger     :: ( Conc :> es        , Exit :> es-       , File :> es+       , Handles :> es        , IdleTimer :> es-       , Input BuildId :> es+       , Input Build.Id :> es        , Log :> es        , Reader SocketPath :> es-       , State BuildPhase :> es-       , Sub BuildPhase :> es+       , State Build.Phase :> es+       , Sub Build.Phase :> es        , UnixSocket :> es        , Waiters :> es        )@@ -91,24 +96,24 @@     forever do         h <- UnixSocket.accept sock         void $ Conc.forkTry @IOException do-            handleConnection h `finally` File.hClose h+            handleConnection h `finally` Handles.hClose h   handleConnection     :: ( Conc :> es        , Exit :> es-       , File :> es+       , Handles :> es        , IdleTimer :> es-       , Input BuildId :> es+       , Input Build.Id :> es        , Log :> es-       , State BuildPhase :> es-       , Sub BuildPhase :> es+       , State Build.Phase :> es+       , Sub Build.Phase :> es        , Waiters :> es        )     => Handle     -> Eff es () handleConnection h = IdleTimer.withActivity do-    line <- File.hGetLine h+    line <- Handles.hGetLine h     case decode (BSL.fromStrict (encodeUtf8 line)) of         Nothing -> sendJson h (ErrorResponse "invalid request")         Just ClientMessage {clientVersion, payload} -> do@@ -123,11 +128,11 @@ dispatch     :: ( Conc :> es        , Exit :> es-       , File :> es-       , Input BuildId :> es+       , Handles :> es+       , Input Build.Id :> es        , Log :> es-       , State BuildPhase :> es-       , Sub BuildPhase :> es+       , State Build.Phase :> es+       , Sub Build.Phase :> es        , Waiters :> es        )     => Query@@ -143,7 +148,7 @@  quit     :: ( Exit :> es-       , File :> es+       , Handles :> es        , Log :> es        , Waiters :> es        )@@ -159,9 +164,9 @@   respondOnce-    :: ( File :> es-       , Input BuildId :> es-       , State BuildPhase :> es+    :: ( Handles :> es+       , Input Build.Id :> es+       , State Build.Phase :> es        )     => Handle -> Eff es () respondOnce h = do@@ -171,34 +176,34 @@  respondWhenDone     :: ( Conc :> es-       , File :> es-       , Input BuildId :> es-       , State BuildPhase :> es-       , Sub BuildPhase :> es+       , Handles :> es+       , Input Build.Id :> es+       , State Build.Phase :> es+       , Sub Build.Phase :> es        )     => Handle -> Eff es () respondWhenDone h = awaitResult >>= mkBuildState >>= sendJson h   where     awaitResult = Conc.scoped do         progressP <- Conc.fork $ Sub.listenUntil_ \case-            failed@(Build.Failed _) -> Just failed-            finished@(Build.Finished _ _) -> Just finished+            failed@(Build.Phase.Failed _) -> Just failed+            finished@(Build.Phase.Finished _ _) -> Just finished             _ -> Nothing         s <- State.get         waitOrStart progressP s      waitOrStart p = \case-        finished@(Build.Finished _ _) -> pure finished-        failed@(Build.Failed _) -> pure failed+        finished@(Build.Phase.Finished _ _) -> pure finished+        failed@(Build.Phase.Failed _) -> pure failed         _ -> Conc.await p   -- | Stream a JSON object after each state change event. watchStream-    :: ( File :> es-       , Input BuildId :> es-       , State BuildPhase :> es-       , Sub BuildPhase :> es+    :: ( Handles :> es+       , Input Build.Id :> es+       , State Build.Phase :> es+       , Sub Build.Phase :> es        )     => Handle -> Eff es () watchStream h = do@@ -208,11 +213,11 @@         mkBuildState progress >>= sendJson h  -respondDiagnostic :: (File :> es, State BuildPhase :> es) => Int -> Handle -> Eff es ()+respondDiagnostic :: (Handles :> es, State Build.Phase :> es) => Int -> Handle -> Eff es () respondDiagnostic idx h = do     progress <- State.get     case progress of-        Build.Finished result postBuild+        Build.Phase.Finished result postBuild             | not $ Test.anyRunningTests postBuild.testSuites && Eval.phasePending postBuild.evalComments ->                 case result.diagnostics !!? (idx - 1) of                     Nothing ->@@ -223,17 +228,17 @@                                 <> " (current build has "                                 <> show (length result.diagnostics)                                 <> ")"-                    Just d -> sendJson h (d :: Diagnostic)+                    Just d -> sendJson h (d :: Build.Diagnostic)             | otherwise -> sendJson h $ ErrorResponse "Build in progress"-        Build.Failed msg -> sendJson h $ ErrorResponse $ "Build command failed:\n" <> msg+        Build.Phase.Failed msg -> sendJson h $ ErrorResponse $ "Build command failed:\n" <> msg         _ -> sendJson h $ ErrorResponse "Build in progress"  -sendJson :: (File :> es, ToJSON a) => Handle -> a -> Eff es ()-sendJson h val = File.hPutTextLn h (decodeUtf8 (BSL.toStrict (encode val))) >> File.hFlush h+sendJson :: (Handles :> es, ToJSON a) => Handle -> a -> Eff es ()+sendJson h val = Handles.hPutTextLn h (decodeUtf8 (BSL.toStrict (encode val))) >> Handles.hFlush h  -mkBuildState :: (Input BuildId :> es) => BuildPhase -> Eff es BuildState+mkBuildState :: (Input Build.Id :> es) => Build.Phase -> Eff es Build.State mkBuildState phase = do     buildId <- input-    pure $ BuildState {buildId, phase}+    pure $ Build.State {buildId, phase}
src/Tricorder/Socket/UnixSocket.hs view
@@ -12,7 +12,8 @@     ) where -import Atelier.Effects.File (BufferMode (..), File, Handle)+import Atelier.Effects.Handles (BufferMode (..), Handle, Handles)+import Atelier.FileSystem.Path (Path) import Effectful (Effect, IOE) import Effectful.Dispatch.Dynamic (interpretWith, localSeqUnlift, reinterpret) import Effectful.Exception (finally)@@ -26,19 +27,20 @@     ) import System.IO (hSetEncoding, utf8) -import Atelier.Effects.File qualified as File+import Atelier.Effects.Handles qualified as Handles+import Atelier.FileSystem.Path qualified as Path import Network.Socket qualified as Net import Network.Socket qualified as Socket   data UnixSocket :: Effect where     -- | Create, bind, and listen on a Unix socket at the given path.-    Bind :: FilePath -> UnixSocket m Socket+    Bind :: (Path path) => path -> UnixSocket m Socket     -- | Accept the next incoming connection and return a line-buffered 'Handle'.     Accept :: Socket -> UnixSocket m Handle     -- | Connect to a Unix socket and run the callback with the resulting handle.     -- The handle is closed when the callback returns.-    WithConnection :: FilePath -> (Handle -> m a) -> UnixSocket m a+    WithConnection :: (Path path) => path -> (Handle -> m a) -> UnixSocket m a   makeEffect ''UnixSocket@@ -49,11 +51,11 @@ -- Socket creation and encoding setup require raw IO (no @File@ equivalent), -- but the handle-level reads, writes, buffering and closing go through the -- 'File' effect.-runIO :: (File :> es, IOE :> es) => Eff (UnixSocket : es) a -> Eff es a+runIO :: (Handles :> es, IOE :> es) => Eff (UnixSocket : es) a -> Eff es a runIO eff = interpretWith eff \env -> \case     Bind path -> liftIO do         sock <- Socket.socket AF_UNIX Stream Socket.defaultProtocol-        Socket.bind sock (SockAddrUnix path)+        Socket.bind sock (SockAddrUnix $ Path.toFilePath path)         Socket.listen sock 5         pure sock     Accept sock -> do@@ -62,18 +64,18 @@             h <- Socket.socketToHandle conn ReadWriteMode             hSetEncoding h utf8             pure h-        File.hSetBuffering h LineBuffering+        Handles.hSetBuffering h LineBuffering         pure h     WithConnection sockPath callback ->         localSeqUnlift env \unlift -> do             h <- liftIO do                 sock <- Socket.socket AF_UNIX Stream Socket.defaultProtocol-                Net.connect sock (SockAddrUnix sockPath)+                Net.connect sock (SockAddrUnix $ Path.toFilePath sockPath)                 h <- Socket.socketToHandle sock ReadWriteMode                 hSetEncoding h utf8                 pure h-            File.hSetBuffering h LineBuffering-            unlift (callback h) `finally` File.hClose h+            Handles.hSetBuffering h LineBuffering+            unlift (callback h) `finally` Handles.hClose h   -- | Script element for the test interpreter.@@ -97,7 +99,7 @@ -- 'socketFileExists' pops the next 'NextFileCheck' entry. -- 'withConnection' pops the next 'NextConnect' entry and passes it to the callback. runScripted-    :: (File :> es, IOE :> es) => [SocketScript] -> Eff (UnixSocket : es) a -> Eff es a+    :: (Handles :> es, IOE :> es) => [SocketScript] -> Eff (UnixSocket : es) a -> Eff es a runScripted script = reinterpret (evalState script) \env -> \case     Bind _ ->         liftIO $ Net.socket AF_UNIX Stream Socket.defaultProtocol@@ -105,7 +107,7 @@         get >>= \case             NextAccept h : rest -> do                 put rest-                File.hSetBuffering h LineBuffering+                Handles.hSetBuffering h LineBuffering                 pure h             _ -> error "UnixSocketScripted: expected NextAccept but queue was empty or mismatched"     WithConnection _ callback ->
src/Tricorder/SourceLookup.hs view
@@ -5,10 +5,10 @@     ) where -import Atelier.Effects.FileSystem (FileSystem, doesFileExist, readFileLbs) import Atelier.Effects.Input (Input) import Atelier.Effects.Log (Log)-import System.FilePath (normalise, takeDirectory, (</>))+import Atelier.FileSystem.Path ((<.>), (</>))+import Effectful.FileSystem (FileSystem) import Tricorder.SourceLookup.ModuleSourceResult (ModuleSourceResult (..)) import Tricorder.SourceLookup.PackageId (PackageId (..)) import Tricorder.SourceLookup.ReexportLimits (ReexportLimits (..))@@ -16,6 +16,8 @@  import Atelier.Effects.Input qualified as Input import Atelier.Effects.Log qualified as Log+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path import Data.Set qualified as Set import Data.Text qualified as T import Tricorder.SourceLookup.ModuleSourceResult qualified as ModuleSourceResult@@ -42,7 +44,7 @@  -- | The directories holding the project's own modules: the @hs-source-dirs@ of -- every component of every project package, resolved against the package dir.-newtype ProjectSourceDirs = ProjectSourceDirs [FilePath]+newtype ProjectSourceDirs = ProjectSourceDirs [Path.Absolute]     deriving stock (Eq, Show)  @@ -50,13 +52,15 @@ projectSourceDirs cabalFiles =     ProjectSourceDirs         $ ordNub-            [ normalise (takeDirectory cabalFile.projectFilePath </> dir)+            [ Path.normalise $ case dir of+                Path.Relative d -> Path.takeDirectory cabalFile.projectFilePath </> d+                Path.Absolute d -> d             | cabalFile <- cabalFiles-            , dir <- orRoot (allSourceDirs cabalFile.projectPackageDescription)+            , dir <- orRoot (either (const []) id $ allSourceDirs cabalFile.projectPackageDescription)             ]   where     -- A component without @hs-source-dirs@ keeps its sources in the package dir.-    orRoot [] = ["."]+    orRoot [] = [Path.Relative $ Path.relative @"."]     orRoot dirs = dirs  @@ -129,7 +133,7 @@     case mFile of         Just path -> do             Log.debug $ "Source: " <> unModuleName query.moduleName <> " → " <> toText path-            src <- decodeUtf8 . toStrict <$> readFileLbs path+            src <- File.read path             pure (Just InProject, fromModuleSource query src)         Nothing -> do             mPkg <- (<|> fallback) <$> resolvePackage query.moduleName@@ -147,13 +151,17 @@ -- candidate path, in source dir then extension order, that exists. findProjectModule     :: (FileSystem :> es)-    => ProjectSourceDirs -> ModuleName -> Eff es (Maybe FilePath)+    => ProjectSourceDirs -> ModuleName -> Eff es (Maybe Path.Absolute) findProjectModule (ProjectSourceDirs dirs) modName =-    firstExisting [dir </> relPath <> toString ext | dir <- dirs, ext <- sourceExtensions]+    firstExisting+        [ dir </> relPath <.> toString rawExt+        | dir <- dirs+        , rawExt <- sourceExtensions+        , Right relPath <- one $ Path.fromFilePath $ toString $ T.replace "." "/" (unModuleName modName)+        ]   where-    relPath = toString $ T.replace "." "/" (unModuleName modName)     firstExisting [] = pure Nothing-    firstExisting (path : rest) = ifM (doesFileExist path) (pure (Just path)) (firstExisting rest)+    firstExisting (path : rest) = ifM (File.exists path) (pure (Just path)) (firstExisting rest)   -- | The result of a query against the source of the module it names.@@ -267,6 +275,7 @@ serveFromTarball query p =     obtainTarball p >>= \case         TarballFetchFailed -> pure $ SourceUnavailable query p+        TarballAddFailed -> pure $ SourceUnavailable query p         TarballAbsent -> pure $ SourceUnavailable query p         TarballAt tarball -> do             mModuleSrc <- readModuleMember tarball query.moduleName
src/Tricorder/SourceLookup/PackageStore.hs view
@@ -7,22 +7,25 @@ where  import Atelier.Effects.Env (Env)-import Atelier.Effects.FileSystem (FileSystem)+import Atelier.FileSystem.Path ((</>)) import Effectful (Effect) import Effectful.Dispatch.Dynamic (interpretWith_)+import Effectful.Exception (trySync)+import Effectful.FileSystem (FileSystem) import Effectful.NonDet (NonDet, OnEmptyPolicy (..), emptyEff, plusEff, runNonDet) import Effectful.TH (makeEffect)-import System.FilePath (takeDirectory, (</>)) import Tricorder.SourceLookup.PackageId (PackageId (..), splitPackageId)  import Atelier.Effects.Env qualified as Env-import Atelier.Effects.FileSystem qualified as FileSystem+import Atelier.FileSystem.Directory qualified as Directory+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map   data PackageStore :: Effect where-    Add :: PackageId -> ByteString -> PackageStore m FilePath-    GetPath :: PackageId -> PackageStore m (Maybe FilePath)+    Add :: PackageId -> ByteString -> PackageStore m (Either Text Path.Absolute)+    GetPath :: PackageId -> PackageStore m (Maybe Path.Absolute)   makeEffect ''PackageStore@@ -31,112 +34,118 @@ run :: (Env :> es, FileSystem :> es) => Eff (PackageStore : es) a -> Eff es a run act = do     storeBaseDir <- findStoreBaseDir-    let packageDir = storeBaseDir </> "packages" </> hackageRepo-    FileSystem.createDirectoryIfMissing True packageDir+    let packageDir = storeBaseDir </> Path.rel @"packages" </> hackageRepo+    Directory.createIfMissing True packageDir     interpretWith_ act \case         Add packageId bytes -> do-            let path = packagePath packageDir packageId-            exists <- FileSystem.doesPathExist path-            unless exists do-                FileSystem.createDirectoryIfMissing True (takeDirectory path)-                FileSystem.writeFileBS path bytes-            pure path+            let mPath = packagePath packageDir packageId+            case mPath of+                Nothing -> pure $ Left $ "Could not create a valid store path for package: " <> show packageId+                Just path -> do+                    exists <- Path.exists path+                    unless exists do+                        Directory.createIfMissing True (Path.takeDirectory path)+                        File.write path bytes+                    pure $ Right path         GetPath packageId -> do-            let path = packagePath packageDir packageId-            exists <- FileSystem.doesPathExist path-            if exists-                then-                    pure $ Just path-                else-                    pure Nothing+            let mPath = packagePath packageDir packageId+            case mPath of+                Nothing -> pure Nothing+                Just path -> do+                    exists <- Path.exists path+                    if exists+                        then pure $ Just path+                        else pure Nothing  -packagePath :: FilePath -> PackageId -> FilePath+packagePath :: Path.Absolute -> PackageId -> Maybe Path.Absolute packagePath packageDir packageId =-    packageDir-        </> toString packageName-        </> toString packageVersion-        </> toString (packageId.unPackageId <> ".tar.gz")+    mkPackagePath+        <$> mkPath packageName+        <*> mkPath packageVersion+        <*> mkPath (packageId.unPackageId <> ".tar.gz")   where+    mkPackagePath pn pv fn = packageDir </> pn </> pv </> fn     (packageName, packageVersion) = splitPackageId packageId+    mkPath = rightToMaybe . Path.fromFilePath . toString  -hackageRepo :: FilePath-hackageRepo = "hackage.haskell.org"+hackageRepo :: Path.Relative+hackageRepo = Path.rel @"hackage.haskell.org"  -findStoreBaseDir :: (Env :> es, FileSystem :> es) => Eff es FilePath+findStoreBaseDir :: (Env :> es, FileSystem :> es) => Eff es Path.Absolute findStoreBaseDir = do     env <- Map.fromList <$> Env.all     fmap (fromMaybe tempFallback . rightToMaybe)         $ runNonDet OnEmptyKeep         $ findCabalDirCandidate env-            `plusEff` findXdgCandidate env-            `plusEff` findHomeCandidate env-            `plusEff` findFallback env+            `plusEff` findXdgCandidate+            `plusEff` findHomeCandidate+            `plusEff` findFallback   findCabalDirCandidate     :: (FileSystem :> es, NonDet :> es)-    => Map String String -> Eff es FilePath+    => Map String String -> Eff es Path.Absolute findCabalDirCandidate env =     case Map.lookup "CABAL_DIR" env of         Nothing -> emptyEff-        Just cabalDir -> getDir cabalDir+        Just cabalDir -> getDir =<< toPath cabalDir   findXdgCandidate     :: (FileSystem :> es, NonDet :> es)-    => Map String String -> Eff es FilePath-findXdgCandidate env =-    case Map.lookup "XDG_CACHE_HOME" env of-        Nothing -> emptyEff-        Just cacheHome -> getDir $ cacheHome </> "cabal"+    => Eff es Path.Absolute+findXdgCandidate = do+    trySync (Directory.getXdg Directory.XdgCache (Path.rel @"cabal")) >>= \case+        Left _ -> emptyEff+        Right dir -> getDir dir  -findHomeCandidate-    :: (FileSystem :> es, NonDet :> es)-    => Map String String -> Eff es FilePath-findHomeCandidate env =-    case Map.lookup "HOME" env of-        Nothing -> emptyEff-        Just home -> do-            let cacheCandidate = home </> ".cache" </> "cabal"-                homeCandidate = home </> ".cabal"+findHomeCandidate :: (FileSystem :> es, NonDet :> es) => Eff es Path.Absolute+findHomeCandidate = do+    trySync Directory.getHome >>= \case+        Left _ -> emptyEff+        Right home -> do+            let cacheCandidate = home </> Path.rel @".cache" </> Path.rel @"cabal"+                homeCandidate = home </> Path.rel @".cabal"             getDir cacheCandidate                 `plusEff` getDir homeCandidate  -findFallback :: (NonDet :> es) => Map String String -> Eff es FilePath-findFallback env =-    findXdgFallback env-        `plusEff` findHomeFallback env+findFallback :: (FileSystem :> es, NonDet :> es) => Eff es Path.Absolute+findFallback = findXdgFallback `plusEff` findHomeFallback  -findXdgFallback :: (NonDet :> es) => Map String String -> Eff es FilePath-findXdgFallback env =-    case Map.lookup "XDG_CACHE_HOME" env of-        Nothing -> emptyEff-        Just cacheHome -> pure $ cacheHome </> "cabal"+findXdgFallback :: (FileSystem :> es, NonDet :> es) => Eff es Path.Absolute+findXdgFallback = do+    trySync (Directory.getXdg Directory.XdgCache $ Path.rel @"cabal") >>= \case+        Left _ -> emptyEff+        Right dir -> pure dir  -findHomeFallback :: (NonDet :> es) => Map String String -> Eff es FilePath-findHomeFallback env =-    case Map.lookup "HOME" env of-        Nothing -> emptyEff-        Just home ->-            pure $ home </> ".cabal"+findHomeFallback :: (FileSystem :> es, NonDet :> es) => Eff es Path.Absolute+findHomeFallback = do+    trySync Directory.getHome >>= \case+        Left _ -> emptyEff+        Right home -> pure $ home </> Path.rel @".cabal"  -tempFallback :: FilePath-tempFallback = "/tmp/tricorder/packages"+tempFallback :: Path.Absolute+tempFallback = Path.absolute @"/tmp/tricorder/packages"  -getDir :: (FileSystem :> es, NonDet :> es) => FilePath -> Eff es FilePath+getDir :: (FileSystem :> es, NonDet :> es) => Path.Absolute -> Eff es Path.Absolute getDir fp = do-    exists <- FileSystem.doesDirectoryExist fp+    exists <- Directory.exists fp     if exists-        then-            pure fp-        else-            emptyEff+        then pure fp+        else emptyEff+++toPath :: (NonDet :> es) => FilePath -> Eff es Path.Absolute+toPath fp =+    case Path.fromFilePath fp of+        Left _ -> emptyEff+        Right d -> pure d
src/Tricorder/SourceLookup/Tarball.hs view
@@ -15,15 +15,17 @@     ) where -import Atelier.Effects.FileSystem (FileSystem, readFileLbs) import Atelier.Effects.Log (Log) import Data.Char (isUpper) import Effectful.Exception (trySync)+import Effectful.FileSystem (FileSystem) import System.FilePath (splitDirectories, (</>)) import Tricorder.SourceLookup.PackageId (PackageId (..), splitPackageId) import Tricorder.SourceLookup.SourceQuery (ModuleName (..))  import Atelier.Effects.Log qualified as Log+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path import Codec.Archive.Tar qualified as Tar import Codec.Compression.GZip qualified as GZip import Data.ByteString.Lazy qualified as BSL@@ -41,12 +43,15 @@  -- | The result of locating (and, if needed, fetching) a package's tarball. data TarballOutcome-    = TarballAt FilePath+    = TarballAt Path.Absolute     | -- | No tarball, though the lookup completed cleanly (absent from every       -- configured repository, or yanked).       TarballAbsent     | -- | The on-demand @cabal fetch@ itself failed (offline, stale index, …).       TarballFetchFailed+    | -- | The tarball was fetched, but could not be stored (no valid store+      -- path could be built for the package).+      TarballAddFailed     deriving stock (Eq, Show)  @@ -69,17 +74,22 @@                     pure $ TarballFetchFailed                 Hackage.Success bytes -> do                     Log.info $ "Storing tarball for " <> pkgId.unPackageId-                    path <- PackageStore.add pkgId bytes-                    Log.info $ "Tarball stored at " <> toText path-                    pure $ TarballAt path+                    addResult <- PackageStore.add pkgId bytes+                    case addResult of+                        Left err -> do+                            Log.err $ "Could not add package to store path: " <> err+                            pure TarballAddFailed+                        Right path -> do+                            Log.info $ "Tarball stored at " <> toText path+                            pure $ TarballAt path   -- | Read a single module's source from a tarball, in-process. 'Nothing' when -- the member is absent or the archive cannot be read (any decompression or -- parse error is caught, never propagated).-readModuleMember :: (FileSystem :> es) => FilePath -> ModuleName -> Eff es (Maybe Text)+readModuleMember :: (FileSystem :> es) => Path.Absolute -> ModuleName -> Eff es (Maybe Text) readModuleMember tarball modName = do-    raw <- readFileLbs tarball+    raw <- File.read tarball     -- 'force' drives the lazy gunzip + tar parse to completion inside 'trySync',     -- so a corrupt archive yields 'Nothing' instead of a deferred exception.     result <- trySync (pure $! force (extractModule modName raw))
+ test/Unit/Tricorder/Build/StateSpec.hs view
@@ -0,0 +1,105 @@+module Unit.Tricorder.Build.StateSpec (test_State) where++import Data.Aeson (eitherDecode, encode)+import Data.Time (UTCTime (..), fromGregorian)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++import Atelier.FileSystem.Path qualified as Path++import Tricorder.Build.Diagnostic (Diagnostic (..))+import Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..))+import Tricorder.Build.Duration (Duration (..))+import Tricorder.Build.Id (Id (..))+import Tricorder.Build.Phase (Phase (..))+import Tricorder.Build.PostBuild (PostBuild (..))+import Tricorder.Build.Result (Result (..))+import Tricorder.Build.State (State (..))++import Tricorder.Build.EvalComment qualified as Eval+import Tricorder.Build.Severity qualified as Severity+++test_State :: TestTree+test_State =+    testGroup+        "Tricorder.Build.State"+        [ testGroup+            "JSON round-trip"+            [ testCase "survives Unicode smart quotes in message text" do+                let msg =+                        Diagnostic+                            { severity = Severity.Warning+                            , file = Location (Path.Relative (Path.rel @"<interactive>"))+                            , line = 2+                            , col = 8+                            , endLine = 2+                            , endCol = 8+                            , title = "Found \8216qualified\8217 in prepositive position"+                            , text =+                                "Found \8216qualified\8217 in prepositive position\n    Suggested fixes:\n      \8226 Place \8216qualified\8217 after the module name."+                            }+                    bs = mkBuildState [msg]+                eitherDecode (encode bs) @?= Right bs+            , testCase "survives control characters in message text" do+                let msg =+                        Diagnostic+                            { severity = Severity.Warning+                            , file = Location (Path.Relative (Path.rel @"<interactive>"))+                            , line = 1+                            , col = 1+                            , endLine = 1+                            , endCol = 1+                            , title = "text with \CAN control \EM chars and \ESC[1m ANSI \ESC[0m codes"+                            , text = "text with \CAN control \EM chars and \ESC[1m ANSI \ESC[0m codes"+                            }+                    bs = mkBuildState [msg]+                eitherDecode (encode bs) @?= Right bs+            , testCase "survives curly double quotes in message text" do+                let msg =+                        Diagnostic+                            { severity = Severity.Warning+                            , file = Location (Path.Relative (Path.rel @"<interactive>"))+                            , line = 1+                            , col = 1+                            , endLine = 1+                            , endCol = 1+                            , title = "\8220Place qualified after the module name.\8221"+                            , text = "\8220Place qualified after the module name.\8221"+                            }+                    bs = mkBuildState [msg]+                eitherDecode (encode bs) @?= Right bs+            , -- Guards the wire format for the BuildFailed phase: the captured+              -- cabal/build error (multi-line, Unicode) must round-trip intact so+              -- the CLI/UI clients can render it.+              testCase "survives a BuildFailed phase with a multi-line message" do+                let bs =+                        mkBuildState [] :: State+                    failed =+                        bs+                            { phase =+                                Failed+                                    "cabal: Could not resolve dependencies:\n[__0] trying: \8216base\8217\nrejecting: ..."+                            }+                eitherDecode (encode failed) @?= Right failed+            ]+        ]+++mkBuildState :: [Diagnostic] -> State+mkBuildState msgs =+    State+        { buildId = Id 1+        , phase =+            Finished+                ( Result+                    { completedAt = epoch+                    , duration = Duration 0+                    , moduleCount = 0+                    , diagnostics = msgs+                    }+                )+                $ PostBuild mempty Eval.NoneFound+        }+  where+    epoch = UTCTime (fromGregorian 1970 1 1) 0
test/Unit/Tricorder/CLI/RenderSpec.hs view
@@ -3,12 +3,16 @@ import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (Assertion, assertBool, testCase) +import Atelier.FileSystem.Path qualified as Path import Data.Text qualified as T -import Tricorder.Build (Diagnostic (..), Severity (..))+import Tricorder.Build.Diagnostic (Diagnostic (..))+import Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..)) import Tricorder.CLI.Render (diagnosticBlock) +import Tricorder.Build.Severity qualified as Severity + test_Render :: TestTree test_Render =     testGroup@@ -40,8 +44,8 @@ errMsg :: Diagnostic errMsg =     Diagnostic-        { severity = SError-        , file = "Foo.hs"+        { severity = Severity.Error+        , file = Location (Path.Relative (Path.rel @"Foo.hs"))         , line = 10         , col = 1         , endLine = 10@@ -54,8 +58,8 @@ warnMsg :: Diagnostic warnMsg =     Diagnostic-        { severity = SWarning-        , file = "Bar.hs"+        { severity = Severity.Warning+        , file = Location (Path.Relative (Path.rel @"Bar.hs"))         , line = 3         , col = 1         , endLine = 3@@ -68,8 +72,8 @@ mixedMsg :: Diagnostic mixedMsg =     Diagnostic-        { severity = SError-        , file = "Baz.hs"+        { severity = Severity.Error+        , file = Location (Path.Relative (Path.rel @"Baz.hs"))         , line = 5         , col = 1         , endLine = 5
− test/Unit/Tricorder/Daemon/BuildStateSpec.hs
@@ -1,104 +0,0 @@-module Unit.Tricorder.Daemon.BuildStateSpec (test_BuildState) where--import Data.Aeson (eitherDecode, encode)-import Data.Time (UTCTime (..), fromGregorian)-import Test.Tasty (TestTree, testGroup)-import Test.Tasty.HUnit (testCase, (@?=))--import Tricorder.Build-    ( BuildId (..)-    , BuildResult (..)-    , BuildState (..)-    , Diagnostic (..)-    , PostBuild (..)-    , Severity (..)-    )-import Tricorder.Build.Duration (Duration (..))--import Tricorder.Build qualified as Build-import Tricorder.Build.EvalComment qualified as Eval---test_BuildState :: TestTree-test_BuildState =-    testGroup-        "BuildState"-        [ testGroup-            "JSON round-trip"-            [ testCase "survives Unicode smart quotes in message text" do-                let msg =-                        Diagnostic-                            { severity = SWarning-                            , file = "<interactive>"-                            , line = 2-                            , col = 8-                            , endLine = 2-                            , endCol = 8-                            , title = "Found \8216qualified\8217 in prepositive position"-                            , text =-                                "Found \8216qualified\8217 in prepositive position\n    Suggested fixes:\n      \8226 Place \8216qualified\8217 after the module name."-                            }-                    bs = mkBuildState [msg]-                eitherDecode (encode bs) @?= Right bs-            , testCase "survives control characters in message text" do-                let msg =-                        Diagnostic-                            { severity = SWarning-                            , file = "<interactive>"-                            , line = 1-                            , col = 1-                            , endLine = 1-                            , endCol = 1-                            , title = "text with \CAN control \EM chars and \ESC[1m ANSI \ESC[0m codes"-                            , text = "text with \CAN control \EM chars and \ESC[1m ANSI \ESC[0m codes"-                            }-                    bs = mkBuildState [msg]-                eitherDecode (encode bs) @?= Right bs-            , testCase "survives curly double quotes in message text" do-                let msg =-                        Diagnostic-                            { severity = SWarning-                            , file = "<interactive>"-                            , line = 1-                            , col = 1-                            , endLine = 1-                            , endCol = 1-                            , title = "\8220Place qualified after the module name.\8221"-                            , text = "\8220Place qualified after the module name.\8221"-                            }-                    bs = mkBuildState [msg]-                eitherDecode (encode bs) @?= Right bs-            , -- Guards the wire format for the BuildFailed phase: the captured-              -- cabal/build error (multi-line, Unicode) must round-trip intact so-              -- the CLI/UI clients can render it.-              testCase "survives a BuildFailed phase with a multi-line message" do-                let bs =-                        mkBuildState [] :: BuildState-                    failed =-                        bs-                            { phase =-                                Build.Failed-                                    "cabal: Could not resolve dependencies:\n[__0] trying: \8216base\8217\nrejecting: ..."-                            }-                eitherDecode (encode failed) @?= Right failed-            ]-        ]---mkBuildState :: [Diagnostic] -> BuildState-mkBuildState msgs =-    BuildState-        { buildId = BuildId 1-        , phase =-            Build.Finished-                ( BuildResult-                    { completedAt = epoch-                    , duration = Duration 0-                    , moduleCount = 0-                    , diagnostics = msgs-                    }-                )-                $ PostBuild mempty Eval.NoneFound-        }-  where-    epoch = UTCTime (fromGregorian 1970 1 1) 0
test/Unit/Tricorder/Daemon/BuilderSpec.hs view
@@ -4,17 +4,22 @@ import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (testCase, (@?=)) +import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map import Data.Set qualified as Set -import Tricorder.Build (BuildResult (..), Diagnostic (..), Severity (..))+import Tricorder.Build.Diagnostic (Diagnostic (..))+import Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..)) import Tricorder.Build.Duration (Duration (..))+import Tricorder.Build.Result (Result (..)) import Tricorder.Daemon.Builder (NewLoadResult (..), compileBuildResults) import Tricorder.Daemon.Ghci.LoadResult (LoadResult (..))-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.WatchDirs (WatchDirs (..)) +import Tricorder.Build.Severity qualified as Severity + test_Builder :: TestTree test_Builder =     testGroup@@ -41,7 +46,7 @@                         , loadResult =                             LoadResult                                 { moduleCount = 2-                                , compiledFiles = Set.singleton errMsg.file+                                , compiledFiles = Set.singleton errPath                                 , loadedModules = Map.empty                                 , targetNames = []                                 , diagnostics = []@@ -49,15 +54,16 @@                         }         r.duration @?= Duration 10_000     , testCase "merges with existing results" do+        let oldWarn = errMsg {severity = Severity.Warning}         let (m, _) =-                compileBuildResults root watchDirs (Map.fromList [(errMsg.file, [errMsg])])+                compileBuildResults root watchDirs (Map.fromList [(errMsg.file, [oldWarn])])                     $ NewLoadResult                         { startTime = epoch                         , endTime = epoch                         , loadResult =                             LoadResult                                 { moduleCount = 2-                                , compiledFiles = Set.singleton warnMsg.file+                                , compiledFiles = Set.singleton warnPath                                 , loadedModules = Map.empty                                 , targetNames = []                                 , diagnostics = [warnMsg]@@ -66,7 +72,7 @@         m             @?= fromList                 [ (warnMsg.file, [warnMsg])-                , (errMsg.file, [errMsg])+                , (errMsg.file, [oldWarn])                 ]     , testCase "returns a BuildResult" do         let (_, r) =@@ -77,14 +83,14 @@                         , loadResult =                             LoadResult                                 { moduleCount = 2-                                , compiledFiles = Set.singleton warnMsg.file+                                , compiledFiles = Set.singleton warnPath                                 , loadedModules = Map.empty                                 , targetNames = []                                 , diagnostics = [warnMsg]                                 }                         }             expected =-                BuildResult+                Result                     { completedAt = addUTCTime 10 epoch                     , duration = Duration 10_000                     , moduleCount = 2@@ -93,19 +99,27 @@         r @?= expected     ]   where-    root = ProjectRoot "/"-    watchDirs = WatchDirs ["/src"]+    root = ProjectRoot (Path.absolute @"/")+    watchDirs = WatchDirs [Path.absolute @"/src"]   -------------------------------------------------------------------------------- -- Helpers -------------------------------------------------------------------------------- +errPath :: Path.Any+errPath = Path.Relative (Path.rel @"./src/Foo.hs")+++warnPath :: Path.Any+warnPath = Path.Relative (Path.rel @"./src/Bar.hs")++ errMsg :: Diagnostic errMsg =     Diagnostic-        { severity = SError-        , file = "./src/Foo.hs"+        { severity = Severity.Error+        , file = Location errPath         , line = 1         , col = 1         , endLine = 1@@ -118,8 +132,8 @@ warnMsg :: Diagnostic warnMsg =     Diagnostic-        { severity = SWarning-        , file = "./src/Bar.hs"+        { severity = Severity.Warning+        , file = Location warnPath         , line = 10         , col = 3         , endLine = 10
test/Unit/Tricorder/Daemon/DispatchSpec.hs view
@@ -3,22 +3,31 @@ import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (assertBool, testCase, (@?=)) +import Atelier.Effects.FileWatcher.Event qualified as Event+import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map import Data.Set qualified as Set -import Tricorder.Build (Diagnostic (..), Severity (..))+import Tricorder.Build.Diagnostic (Diagnostic (..))+import Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..)) import Tricorder.Daemon.Dispatch-    ( KnownTargetNames (..)+    ( DispatchAction (..)+    , KnownTargetNames (..)+    , dispatch     , fileMatchesAnyTarget     , filterToWatchDirs     , mergeDiagnostics+    , planActions     , preserveFailureVisibility     ) import Tricorder.Daemon.Ghci.LoadResult (LoadResult (..))+import Tricorder.Daemon.Ghci.LoadedModule (LoadedModule (..)) import Tricorder.Daemon.Ghci.Result (collectResult) import Tricorder.Session.WatchDirs (WatchDirs (..)) +import Tricorder.Build.Severity qualified as Severity + test_Dispatch :: TestTree test_Dispatch =     testGroup@@ -26,6 +35,8 @@         [ testGroup "fileMatchesAnyTarget" testFileMatchesAnyTarget         , testGroup "mergeDiagnostics" testMergeDiagnostics         , testGroup "filterToWatchDirs" testFilterToWatchDirs+        , testGroup "planActions" testPlanActions+        , testGroup "dispatch" testDispatch         ]  @@ -38,44 +49,44 @@     [ testCase "matches when the path's uppercase-suffix equals a target" do         fileMatchesAnyTarget             (KnownTargetNames (Set.singleton "Tricorder.Version"))-            "./tricorder/src/Tricorder/Version.hs"+            (Path.rel @"./tricorder/src/Tricorder/Version.hs")             @?= True     , testCase "matches a single-segment module" do         fileMatchesAnyTarget             (KnownTargetNames (Set.singleton "Main"))-            "./app/Main.hs"+            (Path.rel @"./app/Main.hs")             @?= True     , testCase "does not match when no uppercase-suffix equals a target" do         fileMatchesAnyTarget             (KnownTargetNames (Set.singleton "Other.Module"))-            "./tricorder/src/Tricorder/Version.hs"+            (Path.rel @"./tricorder/src/Tricorder/Version.hs")             @?= False     , testCase "does not match a lowercase-prefix even if textually contained" do         fileMatchesAnyTarget             (KnownTargetNames (Set.singleton "src.Tricorder.Version"))-            "./tricorder/src/Tricorder/Version.hs"+            (Path.rel @"./tricorder/src/Tricorder/Version.hs")             @?= False     , testCase "handles .lhs extension" do         fileMatchesAnyTarget             (KnownTargetNames (Set.singleton "Foo.Bar"))-            "./src/Foo/Bar.lhs"+            (Path.rel @"./src/Foo/Bar.lhs")             @?= True     , -- GHCi renders a target whose module name is ambiguous across home units       -- (every executable/test 'Main') as its source path, e.g. "app/Main.hs".       testCase "matches a path-shaped target on directory-segment boundaries" do         fileMatchesAnyTarget             (KnownTargetNames (Set.singleton "app/Main.hs"))-            "./tricorder/app/Main.hs"+            (Path.rel @"./tricorder/app/Main.hs")             @?= True     , testCase "does not match a path-shaped target on a partial segment" do         fileMatchesAnyTarget             (KnownTargetNames (Set.singleton "pp/Main.hs"))-            "./tricorder/app/Main.hs"+            (Path.rel @"./tricorder/app/Main.hs")             @?= False     , testCase "does not match a path-shaped target for a different file" do         fileMatchesAnyTarget             (KnownTargetNames (Set.singleton "daemon/Main.hs"))-            "./tricorder/app/Main.hs"+            (Path.rel @"./tricorder/app/Main.hs")             @?= False     ] @@ -90,65 +101,80 @@         -- Foo has an error, Bar has a warning.         -- Only Foo is recompiled (and fixed). Bar is unchanged, so Bar's         -- warning must survive.-        let prev = Map.fromList [(errMsg.file, [errMsg]), (warnMsg.file, [warnMsg])]+        let prev = Map.fromList [(Location errPath, [errMsg]), (Location warnPath, [warnMsg])]             result =                 LoadResult                     { moduleCount = 2-                    , compiledFiles = Set.singleton errMsg.file+                    , compiledFiles = Set.singleton errPath                     , loadedModules = Map.empty                     , targetNames = []                     , diagnostics = []                     }         let merged = mergeDiagnostics prev result-        Map.lookup warnMsg.file merged @?= Just [warnMsg]+        Map.lookup (Location warnPath) merged @?= Just [warnMsg]+    , testCase "drops retained errors for files not in compiledFiles" do+        -- Foo's error is stale if Foo was skipped (e.g. blocked behind a failing+        -- upstream module): GHC re-emits errors for every module it attempts.+        -- Warnings in the same file are kept.+        let prev = Map.fromList [(Location errPath, [errMsg, errMsg {severity = Severity.Warning}])]+            result =+                LoadResult+                    { moduleCount = 1+                    , compiledFiles = Set.empty+                    , loadedModules = Map.empty+                    , targetNames = []+                    , diagnostics = []+                    }+        let merged = mergeDiagnostics prev result+        Map.lookup (Location errPath) merged @?= Just [errMsg {severity = Severity.Warning}]     , testCase "clears diagnostics when a recompiled file now has no issues" do-        let prev = Map.fromList [(errMsg.file, [errMsg])]+        let prev = Map.fromList [(Location errPath, [errMsg])]             result =                 LoadResult                     { moduleCount = 1-                    , compiledFiles = Set.singleton errMsg.file+                    , compiledFiles = Set.singleton errPath                     , loadedModules = Map.empty                     , targetNames = []                     , diagnostics = []                     }         let merged = mergeDiagnostics prev result-        Map.lookup errMsg.file merged @?= Nothing+        Map.lookup (Location errPath) merged @?= Nothing     , testCase "replaces diagnostics for recompiled files" do         let newErr = errMsg {title = "new error", text = "new error\n"}-            prev = Map.fromList [(errMsg.file, [errMsg])]+            prev = Map.fromList [(Location errPath, [errMsg])]             result =                 LoadResult                     { moduleCount = 1-                    , compiledFiles = Set.singleton errMsg.file+                    , compiledFiles = Set.singleton errPath                     , loadedModules = Map.empty                     , targetNames = []                     , diagnostics = [newErr]                     }         let merged = mergeDiagnostics prev result-        Map.lookup errMsg.file merged @?= Just [newErr]+        Map.lookup (Location errPath) merged @?= Just [newErr]     , testCase "accumulates diagnostics for newly seen files" do         let result =                 LoadResult                     { moduleCount = 1-                    , compiledFiles = Set.singleton warnMsg.file+                    , compiledFiles = Set.singleton warnPath                     , loadedModules = Map.empty                     , targetNames = []                     , diagnostics = [warnMsg]                     }         let merged = mergeDiagnostics Map.empty result-        Map.lookup warnMsg.file merged @?= Just [warnMsg]+        Map.lookup (Location warnPath) merged @?= Just [warnMsg]     , testGroup         "when the cycle reports none"         [ testCase "clears a stale location-less diagnostic" do             -- <no location info> is never in compiledFiles, so without special             -- handling it would persist forever. A cycle with no location-less             -- diagnostic must evict it.-            let noLoc = errMsg {file = "<no location info>"}+            let noLoc = errMsg {file = Locationless}                 prev = Map.fromList [(noLoc.file, [noLoc])]                 result =                     LoadResult                         { moduleCount = 1-                        , compiledFiles = Set.singleton errMsg.file+                        , compiledFiles = Set.singleton errPath                         , loadedModules = Map.empty                         , targetNames = []                         , diagnostics = []@@ -157,7 +183,7 @@             Map.lookup noLoc.file merged @?= Nothing         ]     , testCase "refreshes a location-less diagnostic that is still present" do-        let noLoc = errMsg {file = "<no location info>"}+        let noLoc = errMsg {file = Locationless}             prev = Map.fromList [(noLoc.file, [noLoc])]             result =                 LoadResult@@ -180,46 +206,46 @@ testFilterToWatchDirs =     [ testCase "keeps diagnostics under a watched directory" do         -- ./src/Foo.hs is what toRelative produces for an absolute project file-        let d = errMsg {file = "./src/Foo.hs"}+        let d = errMsg {file = Location errPath}         filterToWatchDirs root watchDirs [d] @?= [d]     , testCase "keeps diagnostics under \".\" watched directory" do-        let d = errMsg {file = "src/Foo.hs"}-        filterToWatchDirs root (WatchDirs ["."]) [d] @?= [d]+        let d = errMsg {file = Location (Path.Relative (Path.rel @"src/Foo.hs"))}+        filterToWatchDirs root (WatchDirs [root]) [d] @?= [d]     , testCase "drops diagnostics from outside the project (e.g. Nix store .h files)" do-        let d = errMsg {file = "/nix/store/abc123/ghcautoconf.h"}+        let d = errMsg {file = Location (Path.Absolute (Path.abs @"/nix/store/abc123/ghcautoconf.h"))}         filterToWatchDirs root watchDirs [d] @?= []     , testCase "drops diagnostics with mangled CPP filenames" do         -- The ghcid parser produces "In file included from <path>" as the file         -- field for GCC-style CPP include-chain messages.-        let d = errMsg {file = "In file included from src/Foo.hs"}+        let d = errMsg {file = Location (Path.Relative (Path.rel @"In file included from src/Foo.hs"))}         filterToWatchDirs root watchDirs [d] @?= []     , testCase "drops mangled CPP filenames when watchDirs is [\".\"] (project root)" do         -- With watchDirs=["."], the watch dir resolves to projectRoot itself.         -- A mangled path joined onto projectRoot would incorrectly start with         -- projectRoot+"/", so this case requires an explicit guard.-        let d = errMsg {file = "In file included from src/Foo.hs"}-        filterToWatchDirs root (WatchDirs ["."]) [d] @?= []+        let d = errMsg {file = Location (Path.Relative (Path.rel @"In file included from src/Foo.hs"))}+        filterToWatchDirs root (WatchDirs [root]) [d] @?= []     , testCase "passes everything through when watchDirs is empty" do-        let d = errMsg {file = "/nix/store/abc123/ghcautoconf.h"}+        let d = errMsg {file = Location (Path.Absolute (Path.abs @"/nix/store/abc123/ghcautoconf.h"))}         filterToWatchDirs root (WatchDirs []) [d] @?= [d]     , testCase "works with the '.' fallback watch dir (whole project root)" do-        let d = errMsg {file = "./src/Foo.hs"}-            nixD = errMsg {file = "/nix/store/abc123/ghcautoconf.h"}-        filterToWatchDirs root (WatchDirs ["."]) [d, nixD] @?= [d]+        let d = errMsg {file = Location errPath}+            nixD = errMsg {file = Location (Path.Absolute (Path.abs @"/nix/store/abc123/ghcautoconf.h"))}+        filterToWatchDirs root (WatchDirs [root]) [d, nixD] @?= [d]     , testGroup         "when diagnostic has no path it"         [ testCase "keeps location-less <no location info> errors" do             -- A home-unit GHC plugin that can't load under --enable-multi-repl             -- produces a <no location info> error. It has no path to test against a             -- watch dir, but must survive or the failed build reads as clean.-            let d = errMsg {file = "<no location info>"}+            let d = errMsg {file = Locationless}             filterToWatchDirs root watchDirs [d] @?= [d]         ]     , testCase "does not treat a real <-prefixed path as a location-less marker" do         -- isLocationLess requires a closing '>'. A real (if exotic) path that         -- merely starts with '<' is an ordinary out-of-watch file and must be         -- dropped, not kept as a build-level marker.-        let d = errMsg {file = "<generated>/Foo.hs"}+        let d = errMsg {file = Location (Path.Relative (Path.rel @"<generated>/Foo.hs"))}         filterToWatchDirs root watchDirs [d] @?= []     , testGroup         "when its only error is out of watch dirs"@@ -242,19 +268,66 @@         ]     ]   where-    root = "/project"-    watchDirs = WatchDirs ["/project/src"]+    root = Path.absolute @"/project"+    watchDirs = WatchDirs [Path.absolute @"/project/src"]  +testPlanActions :: [TestTree]+testPlanActions =+    [ testCase "no actions plans nothing" do+        planActions [] @?= []+    , testCase "repeated reloads collapse into one" do+        planActions [Reload, Reload, Reload] @?= [Reload]+    , testCase "a reload is kept when it is the only action" do+        planActions [Reload] @?= [Reload]+    , testCase "an add subsumes a reload, whichever came first" do+        planActions [Reload, Add fileA] @?= [Add fileA]+        planActions [Add fileA, Reload] @?= [Add fileA]+    , testCase "an unadd subsumes a reload" do+        planActions [Reload, Unadd "A"] @?= [Unadd "A"]+    , testCase "target changes keep their order and are de-duplicated" do+        planActions [Add fileA, Unadd "B", Reload, Add fileA] @?= [Add fileA, Unadd "B"]+    ]+++testDispatch :: [TestTree]+testDispatch =+    [ testCase "removing a loaded module unadds it by name and path" do+        dispatch noTargets (Just loadedA) fileA Event.Removed+            @?= Just (Unadd ("A " <> toText fileA))+    , testCase "removing a target that failed to compile unadds it by path" do+        dispatch (KnownTargetNames (Set.singleton "A")) Nothing fileA Event.Removed+            @?= Just (Unadd (toText fileA))+    , testCase "removing a path-form target that failed to compile unadds it" do+        dispatch (KnownTargetNames (Set.singleton "src/A.hs")) Nothing fileA Event.Removed+            @?= Just (Unadd (toText fileA))+    , testCase "removing a file GHCi never saw does nothing" do+        dispatch noTargets Nothing fileA Event.Removed @?= Nothing+    , testCase "modifying an unknown file adds it" do+        dispatch noTargets Nothing fileA Event.Modified @?= Just (Add fileA)+    ]+  where+    noTargets = KnownTargetNames mempty+    loadedA = LoadedModule {relPath = Path.rel @"./src/A.hs", moduleName = "A"}++ -------------------------------------------------------------------------------- -- Helpers -------------------------------------------------------------------------------- +errPath :: Path.Any+errPath = Path.Relative (Path.rel @"./src/Foo.hs")+++warnPath :: Path.Any+warnPath = Path.Relative (Path.rel @"./src/Bar.hs")++ errMsg :: Diagnostic errMsg =     Diagnostic-        { severity = SError-        , file = "./src/Foo.hs"+        { severity = Severity.Error+        , file = Location errPath         , line = 1         , col = 1         , endLine = 1@@ -267,8 +340,8 @@ warnMsg :: Diagnostic warnMsg =     Diagnostic-        { severity = SWarning-        , file = "./src/Bar.hs"+        { severity = Severity.Warning+        , file = Location warnPath         , line = 10         , col = 3         , endLine = 10@@ -276,3 +349,7 @@         , title = "Unused import"         , text = "Unused import"         }+++fileA :: Path.Any+fileA = Path.Relative $ Path.rel @"./src/A.hs"
test/Unit/Tricorder/Daemon/Ghci/LoadResultSpec.hs view
@@ -3,6 +3,7 @@ import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (testCase, (@?=)) +import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map import Data.Set qualified as Set @@ -28,8 +29,8 @@                     { loadedModules =                         Map.fromList                             [-                                ( "/abs/src/Foo.hs"-                                , LoadedModule {relPath = "./src/Foo.hs", moduleName = "Foo"}+                                ( Path.Absolute (Path.abs @"/abs/src/Foo.hs")+                                , LoadedModule {relPath = Path.rel @"./src/Foo.hs", moduleName = "Foo"}                                 )                             ]                     , targetNames = ["Foo"]@@ -37,8 +38,8 @@         LoadResult.resolveKnownTargets Map.empty result             @?= Map.fromList                 [-                    ( "/abs/src/Foo.hs"-                    , LoadedModule {relPath = "./src/Foo.hs", moduleName = "Foo"}+                    ( Path.Absolute (Path.abs @"/abs/src/Foo.hs")+                    , LoadedModule {relPath = Path.rel @"./src/Foo.hs", moduleName = "Foo"}                     )                 ]     , -- Regression test for the stale-results bug. After a failed compile, the@@ -50,8 +51,8 @@         let prev =                 Map.fromList                     [-                        ( "/abs/src/Foo.hs"-                        , LoadedModule {relPath = "./src/Foo.hs", moduleName = "Foo"}+                        ( Path.Absolute (Path.abs @"/abs/src/Foo.hs")+                        , LoadedModule {relPath = Path.rel @"./src/Foo.hs", moduleName = "Foo"}                         )                     ]             result =@@ -64,8 +65,8 @@         let prev =                 Map.fromList                     [-                        ( "/abs/src/Foo.hs"-                        , LoadedModule {relPath = "./src/Foo.hs", moduleName = "Foo"}+                        ( Path.Absolute (Path.abs @"/abs/src/Foo.hs")+                        , LoadedModule {relPath = Path.rel @"./src/Foo.hs", moduleName = "Foo"}                         )                     ]             result = emptyLr {loadedModules = Map.empty, targetNames = []}
test/Unit/Tricorder/Daemon/Ghci/OutputSpec.hs view
@@ -3,6 +3,8 @@ import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (testCase, (@?=)) +import Atelier.FileSystem.Path qualified as Path+ import Tricorder.Daemon.Ghci.Output (parseShowModules, parseShowTargets)  @@ -31,16 +33,16 @@                 , "Main                     ( app/Main.hs, interpreted )"                 ]         parseShowModules input-            @?= [ ("Tricorder.Build", "src/Tricorder.Build.hs")-                , ("Tricorder.Session", "src/Tricorder/Session.hs")-                , ("Main", "app/Main.hs")+            @?= [ ("Tricorder.Build", Path.Relative (Path.rel @"src/Tricorder.Build.hs"))+                , ("Tricorder.Session", Path.Relative (Path.rel @"src/Tricorder/Session.hs"))+                , ("Main", Path.Relative (Path.rel @"app/Main.hs"))                 ]     , testCase "parses absolute paths" do         parseShowModules ["Lib ( /home/user/project/src/Lib.hs, interpreted )"]-            @?= [("Lib", "/home/user/project/src/Lib.hs")]+            @?= [("Lib", Path.Absolute (Path.abs @"/home/user/project/src/Lib.hs"))]     , testCase "strips ANSI codes before parsing" do         parseShowModules ["\ESC[1mMain\ESC[0m                     ( app/Main.hs, interpreted )"]-            @?= [("Main", "app/Main.hs")]+            @?= [("Main", Path.Relative (Path.rel @"app/Main.hs"))]     ]  
test/Unit/Tricorder/Daemon/Ghci/ProcessSpec.hs view
@@ -35,11 +35,12 @@  import Atelier.Effects.Conc qualified as Conc import Atelier.Effects.Delay qualified as Delay-import Atelier.Effects.File qualified as File+import Atelier.Effects.Handles qualified as Handles import Atelier.Effects.Log qualified as Log import Atelier.Effects.Process qualified as AProc import Atelier.Effects.Process qualified as Atelier.Process import Atelier.Effects.Timeout qualified as Timeout+import Atelier.Types.Semaphore qualified as Sem import Data.Text qualified as T import System.Process qualified as Process import System.Timeout qualified@@ -81,10 +82,10 @@             runEff                 . runWriter @[Message]                 . Log.runWriter-                . File.run+                . Handles.run                 $ do-                    for_ ["line1", "line2", finishMarker 1, "line3"] (File.hPutTextLn w)-                    File.hClose w+                    for_ ["line1", "line2", finishMarker 1, "line3"] (Handles.hPutTextLn w)+                    Handles.hClose w                     Process.drainUntil r (finishMarker 1) (\_ -> pure ())         result @?= ["line1", "line2"]     , testCase "streams each non-marker line to onLine, in order, before returning" do@@ -94,10 +95,10 @@             runEff                 . runWriter @[Message]                 . Log.runWriter-                . File.run+                . Handles.run                 $ do-                    for_ ["a", "b", "c", finishMarker 2] (File.hPutTextLn w)-                    File.hClose w+                    for_ ["a", "b", "c", finishMarker 2] (Handles.hPutTextLn w)+                    Handles.hClose w                     Process.drainUntil r (finishMarker 2) (\l -> liftIO $ modifyIORef' seenRef (l :))         seen <- reverse <$> readIORef seenRef         seen @?= ["a", "b", "c"]@@ -108,13 +109,13 @@             runEff                 . runWriter @[Message]                 . Log.runWriter-                . File.run+                . Handles.run                 $ do                     -- 'finishMarker 5' is a leftover from a prior, interrupted                     -- command; the drain waiting for 'finishMarker 9' must                     -- skip it rather than stopping.-                    for_ ["before", finishMarker 5, "after", finishMarker 9] (File.hPutTextLn w)-                    File.hClose w+                    for_ ["before", finishMarker 5, "after", finishMarker 9] (Handles.hPutTextLn w)+                    Handles.hClose w                     Process.drainUntil r (finishMarker 9) (\_ -> pure ())         result @?= ["before", "after"]     , testCase@@ -125,10 +126,10 @@                 runEff                     . runWriter @[Message]                     . Log.runWriter-                    . File.run+                    . Handles.run                     $ do-                        for_ ["first", "second", "third"] (File.hPutTextLn w)-                        File.hClose w -- EOF before the marker ever arrives+                        for_ ["first", "second", "third"] (Handles.hPutTextLn w)+                        Handles.hClose w -- EOF before the marker ever arrives                         trySync (Process.drainUntil r (finishMarker 1) (\_ -> pure ()))             case outcome of                 Right ls -> assertFailure ("expected UnexpectedExit, got: " <> show ls)@@ -144,9 +145,9 @@             runEff                 . runWriter @[Message]                 . Log.runWriter-                . File.run+                . Handles.run                 $ do-                    File.hClose w+                    Handles.hClose w                     trySync (Process.drainUntil r (finishMarker 1) (\_ -> pure ()))         case outcome of             Right ls -> assertFailure ("expected UnexpectedExit, got: " <> show ls)@@ -170,9 +171,9 @@                 runEff                     . runWriter @[Message]                     . Log.runWriter-                    . File.run+                    . Handles.run                     $ do-                        File.hClose w+                        Handles.hClose w                         trySync (Process.drainUntil r (finishMarker 3) (\_ -> pure ()))             case filter (\m -> m.severity == ERROR) msgs of                 [] -> assertFailure "expected an ERROR log message"@@ -185,10 +186,10 @@             runEff                 . runWriter @[Message]                 . Log.runWriter-                . File.run+                . Handles.run                 $ do-                    for_ ["oops-line-1", "oops-line-2"] (File.hPutTextLn w)-                    File.hClose w+                    for_ ["oops-line-1", "oops-line-2"] (Handles.hPutTextLn w)+                    Handles.hClose w                     trySync (Process.drainUntil r (finishMarker 4) (\_ -> pure ()))         case filter (\m -> m.severity == ERROR) msgs of             [] -> assertFailure "expected an ERROR log message"@@ -236,21 +237,21 @@                 . runConcurrent                 . Timeout.run                 . Delay.runIO-                . File.run+                . Handles.run                 . Log.runNoOp                 . Conc.runIO                 $ do                     -- A stale 'marker 5' (left by a prior interrupted reload)                     -- precedes the fresh command's real output + its 'marker 9'                     -- (state is 'Idle 9', so 'execGhci' waits for marker 9).-                    for_ [marker 5, "out-line", marker 9] (File.hPutTextLn stdoutW)-                    for_ [marker 5, "err-line", marker 9] (File.hPutTextLn stderrW)-                    File.hClose stdoutW-                    File.hClose stderrW+                    for_ [marker 5, "out-line", marker 9] (Handles.hPutTextLn stdoutW)+                    for_ [marker 5, "err-line", marker 9] (Handles.hPutTextLn stderrW)+                    Handles.hClose stdoutW+                    Handles.hClose stderrW                     -- Keep the stdin read-end alive across the write inside                     -- 'execGhci' (otherwise it is GC-finalised → broken pipe).                     r <- Process.exec gp "reload" (\_ -> pure ())-                    File.hClose stdinR+                    Handles.hClose stdinR                     pure r         _ <- (Right <$> stopProcess p) `catch` \(_ :: SomeException) -> pure (Left ())         result @?= ["out-line", "err-line"]@@ -295,20 +296,20 @@                 . runConcurrent                 . Timeout.run                 . Delay.runIO-                . File.run+                . Handles.run                 . Log.runNoOp                 . Conc.runIO                 $ do                     -- Pre-seed the marker on both streams so the drain returns                     -- immediately; we only care about what was written to stdin.-                    File.hPutTextLn stdoutW marker-                    File.hPutTextLn stderrW marker-                    File.hClose stdoutW-                    File.hClose stderrW+                    Handles.hPutTextLn stdoutW marker+                    Handles.hPutTextLn stderrW marker+                    Handles.hClose stdoutW+                    Handles.hClose stderrW                     _ <- Process.exec gp ":reload" (\_ -> pure ())-                    File.hClose stdinW+                    Handles.hClose stdinW                     let readAll acc =-                            trySync (File.hGetLine stdinR) >>= \case+                            trySync (Handles.hGetLine stdinR) >>= \case                                 Left (_ :: SomeException) -> pure (reverse acc)                                 Right l -> readAll (l : acc)                     readAll []@@ -340,13 +341,13 @@                 . runConcurrent                 . Timeout.run                 . Delay.runIO-                . File.run+                . Handles.run                 . Conc.runIO                 $ do                     -- No banner will ever arrive: close the write end so the                     -- wait sees EOF at once and takes the "command exited"                     -- failure branch.-                    File.hClose bannerOutW+                    Handles.hClose bannerOutW                     -- Producer: pause long enough that a snapshot-at-exit reads                     -- an empty buffer, THEN stream the whole error log and                     -- close so the drain sees EOF. A correct implementation@@ -354,8 +355,8 @@                     _ <- Conc.fork do                         Delay.wait (30 :: Millisecond)                         for_ [1 .. lineCount] \i ->-                            File.hPutTextLn errW ("err line " <> show i :: Text)-                        File.hClose errW+                            Handles.hPutTextLn errW ("err line " <> show i :: Text)+                        Handles.hClose errW                     trySync (Process.waitForBannerOrFail (5 :: Second) bannerOut errR)         case result of             Right () -> assertFailure "expected waitForBannerOrFail to throw a startup error"@@ -384,17 +385,17 @@                     . runConcurrent                     . Timeout.run                     . Delay.runIO-                    . File.run+                    . Handles.run                     . Conc.runIO                     . Atelier.Process.run                     $ withProcessGroup procConfig \p -> do                         -- First stdout line is the long-lived child's pid.-                        line <- File.hGetLine (AProc.getStdout p)+                        line <- Handles.hGetLine (AProc.getStdout p)                         liftIO $ writeIORef childPidRef (parsePid (T.unpack line))                         -- Let the leader exit and reap it, so the cleanup runs                         -- with the leader already gone — the path the bug needed.-                        File.hPutTextLn (AProc.getStdin p) ""-                        File.hFlush (AProc.getStdin p)+                        Handles.hPutTextLn (AProc.getStdin p) ""+                        Handles.hFlush (AProc.getStdin p)                         void $ AProc.waitExitCode p         -- Hard wall-clock bound: a regression must surface as a failed         -- assertion, never as a hang that stalls the whole suite.@@ -533,7 +534,7 @@                 . runConcurrent                 . Timeout.run                 . Delay.runIO-                . File.run+                . Handles.run                 . Log.runNoOp                 . Conc.runIO                 $ Conc.scoped do@@ -541,14 +542,16 @@                     -- regresses, the drain exception will tear this scope                     -- down and the sibling will be cancelled before it can                     -- flip the ref.+                    execDone <- Sem.new                     sibling <- Conc.fork do-                        Delay.wait (50 :: Millisecond)+                        Sem.wait execDone                         liftIO (writeIORef siblingDoneRef True)                     -- Drive 'execGhci' on a dead process; the drains should                     -- raise 'UnexpectedExit', which 'trySync' must catch                     -- here rather than letting Ki tear down the scope.                     execResult <- trySync (Process.exec gp "cmd" (\_ -> pure ()))-                    -- Wait for the sibling to run.+                    -- Release the sibling, then wait for it to run.+                    Sem.signal execDone                     Conc.await sibling                     pure execResult         -- stopProcess flushes the buffered command+marker to a pipe whose
test/Unit/Tricorder/Daemon/Ghci/ResultSpec.hs view
@@ -3,14 +3,17 @@ import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (testCase, (@?), (@?=)) -import Tricorder.Build (Severity (..))+import Atelier.FileSystem.Path qualified as Path++import Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..)) import Tricorder.Daemon.Ghci.LoadResult (LoadResult (..)) import Tricorder.Daemon.Ghci.Loading (Loading (..)) import Tricorder.Daemon.Ghci.Message (Message (..)) import Tricorder.Daemon.Ghci.Position (Position (..)) import Tricorder.Daemon.Ghci.Result (collectResult, collectResultCustom, extractTitle, parseReload) -import Tricorder.Build qualified as Build.Diagnostic+import Tricorder.Build.Diagnostic qualified as Build.Diagnostic+import Tricorder.Build.Severity qualified as Build.Severity import Tricorder.Daemon.Ghci.Load qualified as Load import Tricorder.Daemon.Ghci.LoadOutcome qualified as LoadOutcome import Tricorder.Daemon.Ghci.Severity qualified as Severity@@ -119,16 +122,22 @@                         { index = 1                         , total = 3                         , moduleName = "Tricorder.Build"-                        , sourceFile = "src/Tricorder.Build.hs"+                        , sourceFile = Path.Relative (Path.rel @"src/Tricorder.Build.hs")                         }                 , Load.Loading                     Loading                         { index = 2                         , total = 3                         , moduleName = "Tricorder.Session"-                        , sourceFile = "src/Tricorder/Session.hs"+                        , sourceFile = Path.Relative (Path.rel @"src/Tricorder/Session.hs")                         }-                , Load.Loading Loading {index = 3, total = 3, moduleName = "Main", sourceFile = "app/Main.hs"}+                , Load.Loading+                    Loading+                        { index = 3+                        , total = 3+                        , moduleName = "Main"+                        , sourceFile = Path.Relative (Path.rel @"app/Main.hs")+                        }                 , Load.Summary LoadOutcome.LoadSucceeded                 ]     , testCase "handles padded module index (e.g. [ 1 of 47])" do@@ -137,7 +146,13 @@                 , "Ok, 1 module loaded."                 ]         parseReload input-            @?= [ Load.Loading Loading {index = 1, total = 47, moduleName = "Main", sourceFile = "app/Main.hs"}+            @?= [ Load.Loading+                    Loading+                        { index = 1+                        , total = 47+                        , moduleName = "Main"+                        , sourceFile = Path.Relative (Path.rel @"app/Main.hs")+                        }                 , Load.Summary LoadOutcome.LoadSucceeded                 ]     , testGroup@@ -156,7 +171,7 @@             @?= [ Load.Message                     Message                         { severity = Severity.Error-                        , file = "src/Foo.hs"+                        , file = Location (Path.Relative (Path.rel @"src/Foo.hs"))                         , startPos = Position 10 5                         , endPos = Position 10 5                         , messageLines = ["src/Foo.hs:10:5: error: Variable not in scope: foo"]@@ -172,7 +187,7 @@             @?= [ Load.Message                     Message                         { severity = Severity.Warning-                        , file = "src/Bar.hs"+                        , file = Location (Path.Relative (Path.rel @"src/Bar.hs"))                         , startPos = Position 20 3                         , endPos = Position 20 3                         , messageLines =@@ -188,7 +203,7 @@             @?= [ Load.Message                     Message                         { severity = Severity.Error-                        , file = "src/Baz.hs"+                        , file = Location (Path.Relative (Path.rel @"src/Baz.hs"))                         , startPos = Position 5 1                         , endPos = Position 5 10                         , messageLines = ["src/Baz.hs:5:1-10: error: Parse error"]@@ -200,7 +215,7 @@             @?= [ Load.Message                     Message                         { severity = Severity.Error-                        , file = "src/Qux.hs"+                        , file = Location (Path.Relative (Path.rel @"src/Qux.hs"))                         , startPos = Position 3 1                         , endPos = Position 5 20                         , messageLines = ["src/Qux.hs:(3,1)-(5,20): error: Multi-line error"]@@ -212,7 +227,7 @@             @?= [ Load.Message                     Message                         { severity = Severity.Error-                        , file = "src/Qux.hs"+                        , file = Location (Path.Relative (Path.rel @"src/Qux.hs"))                         , startPos = Position 3 1                         , endPos = Position 5 20                         , messageLines = ["src/Qux.hs:(3,1)-((5,20): error: Multi-line error"]@@ -230,7 +245,7 @@             @?= [ Load.Message                     Message                         { severity = Severity.Error-                        , file = "src/Foo.hs"+                        , file = Location (Path.Relative (Path.rel @"src/Foo.hs"))                         , startPos = Position 10 5                         , endPos = Position 10 5                         , messageLines =@@ -248,7 +263,7 @@             @?= [ Load.Message                     Message                         { severity = Severity.Error-                        , file = "src/Foo.hs"+                        , file = Location (Path.Relative (Path.rel @"src/Foo.hs"))                         , startPos = Position 10 5                         , endPos = Position 10 5                         , messageLines = [ansiHeader]@@ -260,7 +275,7 @@             @?= [ Load.Message                     Message                         { severity = Severity.Error-                        , file = "C:\\path\\file.hs"+                        , file = Location (Path.Relative (Path.rel @"C:\\path\\file.hs"))                         , startPos = Position 10 5                         , endPos = Position 10 5                         , messageLines = ["C:\\path\\file.hs:10:5: error: Variable not in scope: foo"]@@ -274,16 +289,28 @@                 , "Failed, 1 module loaded."                 ]         parseReload input-            @?= [ Load.Loading Loading {index = 1, total = 2, moduleName = "Lib", sourceFile = "src/Lib.hs"}+            @?= [ Load.Loading+                    Loading+                        { index = 1+                        , total = 2+                        , moduleName = "Lib"+                        , sourceFile = Path.Relative (Path.rel @"src/Lib.hs")+                        }                 , Load.Message                     Message                         { severity = Severity.Error-                        , file = "src/Lib.hs"+                        , file = Location (Path.Relative (Path.rel @"src/Lib.hs"))                         , startPos = Position 5 1                         , endPos = Position 5 1                         , messageLines = ["src/Lib.hs:5:1: error: Oops"]                         }-                , Load.Loading Loading {index = 2, total = 2, moduleName = "Main", sourceFile = "app/Main.hs"}+                , Load.Loading+                    Loading+                        { index = 2+                        , total = 2+                        , moduleName = "Main"+                        , sourceFile = Path.Relative (Path.rel @"app/Main.hs")+                        }                 , Load.Summary LoadOutcome.LoadFailed                 ]     ]@@ -303,7 +330,7 @@                 @?= [ Load.Message                         Message                             { severity = Severity.Error-                            , file = "src/Foo.hs"+                            , file = Location (Path.Relative (Path.rel @"src/Foo.hs"))                             , startPos = Position 10 5                             , endPos = Position 10 5                             , messageLines =@@ -334,7 +361,7 @@             @?= [ Load.Message                     Message                         { severity = Severity.Error-                        , file = "<no location info>"+                        , file = Locationless                         , startPos = Position 0 0                         , endPos = Position 0 0                         , messageLines =@@ -348,7 +375,7 @@             @?= [ Load.Message                     Message                         { severity = Severity.Error-                        , file = "<no location info>"+                        , file = Locationless                         , startPos = Position 0 0                         , endPos = Position 0 0                         , messageLines = ["<no location info>: error: some error"]@@ -373,7 +400,13 @@                 ]         parseReload input             @?= [ Load.LoadConfig ".ghci"-                , Load.Loading Loading {index = 1, total = 1, moduleName = "Main", sourceFile = "app/Main.hs"}+                , Load.Loading+                    Loading+                        { index = 1+                        , total = 1+                        , moduleName = "Main"+                        , sourceFile = Path.Relative (Path.rel @"app/Main.hs")+                        }                 , Load.Summary LoadOutcome.LoadSucceeded                 ]     ]@@ -399,7 +432,7 @@     -- executable loads a home-unit GHC plugin: the plugin package's modules     -- compile, then the unit using the plugin fails with a location-less error.     [ testCase "surfaces the plugin load failure as an error diagnostic" do-        Build.Diagnostic.SError `elem` map (.severity) result.diagnostics @? "expected an error diagnostic"+        Build.Severity.Error `elem` map (.severity) result.diagnostics @? "expected an error diagnostic"     , testCase "carries the plugin error message in the diagnostic title" do         "Could not load module \8216My.Plugin\8217." `elem` map (.title) result.diagnostics             @? "expected the plugin error message in a diagnostic title"@@ -416,7 +449,7 @@         , "[5 of 5] Compiling Main            ( test/Tests.hs, interpreted )[app-pkg-0.1.0.0-inplace-test]"         , "Failed, 4 modules loaded."         ]-    result = collectResultCustom "/project" (parseReload reloadOutput) [] []+    result = collectResultCustom (Path.absolute @"/project") (parseReload reloadOutput) [] []   testCollectResult :: [TestTree]@@ -438,8 +471,8 @@                     , "[2 of 2] Compiling Main ( app/Main.hs, interpreted )"                     , "Failed, 1 module loaded."                     ]-                result = collectResult "/project" reloadOutput [] []-            map (.severity) result.diagnostics @?= [SError]+                result = collectResult (Path.absolute @"/project") reloadOutput [] []+            map (.severity) result.diagnostics @?= [Build.Severity.Error]         ]     , testCase "does not duplicate a failure that already produced a located error" do         let reloadOutput =@@ -447,15 +480,15 @@                 , "src/Lib.hs:5:1: error: Oops"                 , "Failed, 0 modules loaded."                 ]-            result = collectResult "/project" reloadOutput [] []+            result = collectResult (Path.absolute @"/project") reloadOutput [] []         -- Only the real, located diagnostic — no synthetic one appended.-        map (.file) result.diagnostics @?= ["src/Lib.hs"]+        map (.file) result.diagnostics @?= [Location (Path.Relative (Path.rel @"src/Lib.hs"))]     , testCase "adds nothing for a successful load" do         let reloadOutput =                 [ "[1 of 1] Compiling Main ( app/Main.hs, interpreted )"                 , "Ok, 1 module loaded."                 ]-            result = collectResult "/project" reloadOutput [] []+            result = collectResult (Path.absolute @"/project") reloadOutput [] []         result.diagnostics @?= []     , testGroup         "when 'Failed,' appears off the summary line"@@ -471,7 +504,7 @@                     , "Failed, retrying with fallback" -- printed by a TH splice                     , "Ok, 1 module loaded."                     ]-                result = collectResult "/project" reloadOutput [] []+                result = collectResult (Path.absolute @"/project") reloadOutput [] []             result.diagnostics @?= []         ]     ]
test/Unit/Tricorder/Daemon/Ghci/SessionSpec.hs view
@@ -8,17 +8,21 @@ import Test.Tasty.HUnit (assertBool, testCase, (@?=))  import Atelier.Effects.PubSub.Pub qualified as Pub+import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map import Data.Set qualified as Set -import Tricorder.Build (BuildProgress, Diagnostic (..), Severity (..))+import Tricorder.Build.Diagnostic (Diagnostic (..))+import Tricorder.Build.DiagnosticLocation (DiagnosticLocation (..))+import Tricorder.Build.Progress (Progress) import Tricorder.Daemon.Ghci.Controls (Controls (..)) import Tricorder.Daemon.Ghci.LoadResult (LoadResult (..)) import Tricorder.Daemon.Ghci.Session (Session)-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.Command.RenderedCommand (RenderedCommand (..)) import Tricorder.Session.Stage (Stage (..)) +import Tricorder.Build.Severity qualified as Build.Severity import Tricorder.Daemon.Ghci.Session qualified as Session  @@ -43,18 +47,18 @@             [ testCase "returns scripted messages" do                 LoadResult {diagnostics = msgs} <-                     runScripted [simpleResult [errMsg]]-                        $ Session.with Pub.publish cmd (ProjectRoot "/") \initial _ -> pure initial+                        $ Session.with Pub.publish cmd (ProjectRoot (Path.absolute @"/")) \initial _ -> pure initial                 msgs @?= [errMsg]             , testCase "returns empty list when scripted result has no messages" do                 LoadResult {diagnostics = msgs} <-                     runScripted [simpleResult []]-                        $ Session.with Pub.publish cmd (ProjectRoot "/") \initial _ -> pure initial+                        $ Session.with Pub.publish cmd (ProjectRoot (Path.absolute @"/")) \initial _ -> pure initial                 msgs @?= []             , testCase "throws when scripted result is Left" do                 result <-                     runScripted [Left (toException boom)]                         $ try @ErrorCall-                        $ Session.with Pub.publish cmd (ProjectRoot "/") \initial _ -> pure initial+                        $ Session.with Pub.publish cmd (ProjectRoot (Path.absolute @"/")) \initial _ -> pure initial                 result @?= Left boom             ]         , testGroup@@ -62,13 +66,13 @@             [ testCase "returns scripted messages" do                 LoadResult {diagnostics = msgs} <-                     runScripted [simpleResult [warnMsg], simpleResult [errMsg]]-                        $ Session.with Pub.publish cmd (ProjectRoot "/") \_ controls -> controls.reload+                        $ Session.with Pub.publish cmd (ProjectRoot (Path.absolute @"/")) \_ controls -> controls.reload                 msgs @?= [errMsg]             , testCase "throws when scripted result is Left" do                 result <-                     runScripted [Left (toException boom)]                         $ try @ErrorCall-                        $ Session.with Pub.publish cmd (ProjectRoot "/") \_ controls -> controls.reload+                        $ Session.with Pub.publish cmd (ProjectRoot (Path.absolute @"/")) \_ controls -> controls.reload                 result @?= Left boom             ]         ]@@ -76,15 +80,15 @@         "sequencing"         [ testCase "consumes results in order across mixed operations" do             (a, b) <- runScripted [simpleResult [errMsg], simpleResult [warnMsg]] do-                Session.with Pub.publish cmd (ProjectRoot "/") \LoadResult {diagnostics = a} controls -> do+                Session.with Pub.publish cmd (ProjectRoot (Path.absolute @"/")) \LoadResult {diagnostics = a} controls -> do                     LoadResult {diagnostics = b} <- controls.reload                     pure (a, b)             a @?= [errMsg]             b @?= [warnMsg]         , testCase "recover scenario: error then success" do             result <- runScripted [Left (toException boom), simpleResult []] do-                r1 <- try @ErrorCall $ Session.with Pub.publish cmd (ProjectRoot "/") \i _ -> pure i-                LoadResult {diagnostics = r2} <- Session.with Pub.publish cmd (ProjectRoot "/") \i _ -> pure i+                r1 <- try @ErrorCall $ Session.with Pub.publish cmd (ProjectRoot (Path.absolute @"/")) \i _ -> pure i+                LoadResult {diagnostics = r2} <- Session.with Pub.publish cmd (ProjectRoot (Path.absolute @"/")) \i _ -> pure i                 pure (r1, r2)             assertBool "expected Left" $ isLeft (fst result)             snd result @?= []@@ -107,8 +111,8 @@ errMsg :: Diagnostic errMsg =     Diagnostic-        { severity = SError-        , file = "src/Foo.hs"+        { severity = Build.Severity.Error+        , file = Location (Path.Relative (Path.rel @"src/Foo.hs"))         , line = 1         , col = 1         , endLine = 1@@ -121,8 +125,8 @@ warnMsg :: Diagnostic warnMsg =     Diagnostic-        { severity = SWarning-        , file = "src/Bar.hs"+        { severity = Build.Severity.Warning+        , file = Location (Path.Relative (Path.rel @"src/Bar.hs"))         , line = 10         , col = 3         , endLine = 10@@ -147,6 +151,6 @@  runScripted     :: [Either SomeException LoadResult]-    -> Eff '[Session, Pub BuildProgress, IOE] a+    -> Eff '[Session, Pub Progress, IOE] a     -> IO a runScripted results = runEff . Pub.noOp . Session.runScripted results
test/Unit/Tricorder/Daemon/WatchSpec.hs view
@@ -9,12 +9,13 @@ import Text.Regex.TDFA.ReadRegex (parseRegex)  import Atelier.Effects.PubSub.Pub qualified as Pub+import Atelier.FileSystem.Path qualified as Path -import Tricorder.Build.Changes (CabalChangeDetected (..), SourceChangeDetected (..))+import Tricorder.Build.Changes (ProjectChangeDetected (..), SourceChangeDetected (..)) import Tricorder.Daemon.Watch (WatchedFile (..))-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.WatchDirs (WatchDirs (..))-import Tricorder.Session.WatchExclusionPatterns (WatchExclusionPatterns (..))+import Tricorder.Session.WatchExclusionPatterns (Pattern (..), WatchExclusionPatterns (..))  import Tricorder.Daemon.Watch qualified as Watch @@ -33,14 +34,14 @@     [ testGroup         "with non-cabal file change"         [ testCase "should publish SourceChangeDetected" do-            (_, sourceChanges) <- runTest "foo"-            sourceChanges @?= [SourceChangeDetected "foo" Modified]+            (_, sourceChanges) <- runTest (Path.Relative $ Path.rel @"foo")+            sourceChanges @?= [SourceChangeDetected (Path.Relative $ Path.rel @"foo") Modified]         ]     , testGroup         "with cabal file change"         [ testCase "should publish CabalChangeDetected" do-            (cabalChanges, _) <- runTest "foo.cabal"-            cabalChanges @?= [CabalChangeDetected "foo.cabal" Modified]+            (cabalChanges, _) <- runTest $ Path.Relative $ Path.rel @"foo.cabal"+            cabalChanges @?= [ProjectChangeDetected (Path.Relative $ Path.rel @"foo.cabal") Modified]         ]     ]   where@@ -49,7 +50,7 @@             . runWriter             . Pub.toWriter @SourceChangeDetected             . execWriter-            . Pub.toWriter @CabalChangeDetected+            . Pub.toWriter @ProjectChangeDetected             . Watch.publishChange             . (`WatchedFile` Modified) @@ -61,41 +62,41 @@         [ testCase "matches .hs files in configured watch dirs" do             let watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [])-                        (WatchDirs ["/proj/src"])-            matchesAny watches "/proj/src/Foo.hs" @?= True+                        (WatchDirs [Path.absolute @"/proj/src"])+            matchesAny watches (Path.absolute @"/proj/src/Foo.hs") @?= True         , testCase "does not match non-.hs files" do             let watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [])-                        (WatchDirs ["/proj/src"])-            matchesAny watches "/proj/src/Foo.txt" @?= False+                        (WatchDirs [Path.absolute @"/proj/src"])+            matchesAny watches (Path.absolute @"/proj/src/Foo.txt") @?= False         , testCase "excludes paths containing dist-newstyle" do             let watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [])-                        (WatchDirs ["/proj/src"])-            matchesAny watches "/proj/src/dist-newstyle/Foo.hs" @?= False+                        (WatchDirs [Path.absolute @"/proj/src"])+            matchesAny watches (Path.absolute @"/proj/src/dist-newstyle/Foo.hs") @?= False         , testCase "excludes paths matching an exclusion pattern" do             let pat = parsePattern "vendor"                 watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [pat])-                        (WatchDirs ["/proj/src"])-            matchesAny watches "/proj/src/vendor/Foo.hs" @?= False-            matchesAny watches "/proj/src/Foo.hs" @?= True+                        (WatchDirs [Path.absolute @"/proj/src"])+            matchesAny watches (Path.absolute @"/proj/src/vendor/Foo.hs") @?= False+            matchesAny watches (Path.absolute @"/proj/src/Foo.hs") @?= True         , testCase "matches .hs files across multiple watch dirs" do             let watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [])-                        (WatchDirs ["/proj/src", "/proj/test"])-            matchesAny watches "/proj/src/Foo.hs" @?= True-            matchesAny watches "/proj/test/FooSpec.hs" @?= True+                        (WatchDirs [Path.absolute @"/proj/src", Path.absolute @"/proj/test"])+            matchesAny watches (Path.absolute @"/proj/src/Foo.hs") @?= True+            matchesAny watches (Path.absolute @"/proj/test/FooSpec.hs") @?= True         , -- Second line of defense: 'cabalWatches' registers the whole project           -- root, and 'deduplicateDirs' collapses the narrow source dirs into it,           -- so the OS watches the entire repo recursively. 'matchesAny' is what@@ -104,50 +105,50 @@           testCase "does not match a .hs file in a sibling package outside the watch dirs" do             let watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [])-                        (WatchDirs ["/proj/pkg-a/src"])-            matchesAny watches "/proj/pkg-a/src/Foo.hs" @?= True-            matchesAny watches "/proj/pkg-b/src/Foo.hs" @?= False+                        (WatchDirs [Path.absolute @"/proj/pkg-a/src"])+            matchesAny watches (Path.absolute @"/proj/pkg-a/src/Foo.hs") @?= True+            matchesAny watches (Path.absolute @"/proj/pkg-b/src/Foo.hs") @?= False         ]     , testGroup         "cabal watches"         [ testCase "matches .cabal files under project root" do             let watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [])                         (WatchDirs [])-            matchesAny watches "/proj/foo.cabal" @?= True+            matchesAny watches (Path.absolute @"/proj/foo.cabal") @?= True         , testCase "matches cabal.project under project root" do             let watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [])                         (WatchDirs [])-            matchesAny watches "/proj/cabal.project" @?= True-        , testCase "matches package.yaml under project root" do+            matchesAny watches (Path.absolute @"/proj/cabal.project") @?= True+        , testCase "does not match package.yaml (its .cabal file is watched instead)" do             let watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [])                         (WatchDirs [])-            matchesAny watches "/proj/package.yaml" @?= True+            matchesAny watches (Path.absolute @"/proj/package.yaml") @?= False         , testCase "does not match non-cabal files" do             let watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [])                         (WatchDirs [])-            matchesAny watches "/proj/README.md" @?= False+            matchesAny watches (Path.absolute @"/proj/README.md") @?= False         , testCase "excludes cabal files under dist-newstyle" do             let watches =                     Watch.specs-                        (ProjectRoot "/proj")+                        (ProjectRoot (Path.absolute @"/proj"))                         (WatchExclusionPatterns [])                         (WatchDirs [])-            matchesAny watches "/proj/dist-newstyle/foo.cabal" @?= False+            matchesAny watches (Path.absolute @"/proj/dist-newstyle/foo.cabal") @?= False         ]     ]   where-    parsePattern p = fromRight (error . toText $ "bad test pattern: " <> p) (parseRegex p)+    parsePattern p = Pattern $ fromRight (error . toText $ "bad test pattern: " <> p) (parseRegex p)
+ test/Unit/Tricorder/Runtime/ProjectRootSpec.hs view
@@ -0,0 +1,68 @@+module Unit.Tricorder.Runtime.ProjectRootSpec (test_ProjectRoot) where++import Atelier.FileSystem.Path ((</>))+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++import Atelier.FileSystem.Path qualified as Path+import Data.Map.Strict qualified as Map++import Tricorder.Runtime.ProjectRoot (findFileUpwards, findProjectRoot)+import Unit.Tricorder.Session.Helpers (withProjectFiles)+++test_ProjectRoot :: TestTree+test_ProjectRoot =+    testGroup+        "ProjectRoot"+        [ testGroup+            "findProjectRoot"+            [ testCase "stops at a package directory inside a larger project" do+                actual <- run ["stack.yaml", "pkg/pkg.cabal", "pkg/src/Foo.hs"] (Path.rel @"pkg/src")+                actual @?= Just (Path.rel @"pkg")+            , testCase "finds stack.yaml in an ancestor" do+                actual <- run ["stack.yaml", "pkg/README.md"] (Path.rel @"pkg")+                actual @?= Just (Path.rel @".")+            , testCase "finds cabal.project in the current directory" do+                actual <- run ["cabal.project"] (Path.rel @".")+                actual @?= Just (Path.rel @".")+            , testCase "finds nothing without any project files" do+                actual <- run ["pkg/README.md"] (Path.rel @"pkg")+                -- The temporary directory is created under /tmp, which has no+                -- project files in any ancestor.+                actual @?= Nothing+            ]+        , testGroup+            "findFileUpwards"+            [ testCase "finds stack.yaml above a package directory" do+                actual <- runUp (Path.rel @"stack.yaml") ["stack.yaml", "pkg/pkg.cabal"] (Path.rel @"pkg")+                actual @?= Just (Path.rel @".")+            , testCase "prefers the nearest match" do+                actual <- runUp (Path.rel @"cabal.project") ["cabal.project", "pkg/cabal.project"] (Path.rel @"pkg")+                actual @?= Just (Path.rel @"pkg")+            , testCase "finds nothing when the file is absent" do+                actual <- runUp (Path.rel @"stack.yaml") ["cabal.project"] (Path.rel @".")+                actual @?= Nothing+            ]+        ]+++-- | Run 'findProjectRoot' from a directory inside a temporary project root+-- seeded with empty files, reporting the result relative to that root.+run :: [FilePath] -> Path.Relative -> IO (Maybe Path.Relative)+run files start = withProjectFiles (seed files) \root ->+    fmap (Path.makeRelative root) <$> findProjectRoot (root </> start)+++-- | Run 'findFileUpwards' likewise.+runUp :: Path.Relative -> [FilePath] -> Path.Relative -> IO (Maybe Path.Relative)+runUp name files start = withProjectFiles (seed files) \root ->+    fmap (Path.makeRelative root) <$> findFileUpwards name (root </> start)+++seed :: [FilePath] -> Map Path.Relative ByteString+seed files = Map.fromList [(rel f, "") | f <- files]+++rel :: FilePath -> Path.Relative+rel = either error id . Path.fromFilePath
test/Unit/Tricorder/Session/CabalFileSpec.hs view
@@ -1,19 +1,18 @@ module Unit.Tricorder.Session.CabalFileSpec (test_CabalFile) where +import Atelier.FileSystem.Path ((</>)) import Effectful (runPureEff) import Effectful.Reader.Static (runReader)-import Effectful.State.Static.Shared (evalState)-import Test.Tasty (TestTree, testGroup)+import Test.Tasty (DependencyType (AllFinish), TestTree, dependentTestGroup, testGroup) import Test.Tasty.HUnit (testCase, (@?=)) -import Atelier.Effects.Env qualified as Env-import Atelier.Effects.FileSystem qualified as FileSystem import Atelier.Effects.FileSystem.Glob qualified as Glob import Atelier.Effects.Input qualified as Input import Atelier.Effects.Log qualified as Log+import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.CabalFile     ( CabalFile (..)     , discoverCabalPackages@@ -21,14 +20,22 @@     , readProjectFile     ) import Tricorder.Session.StackProject (StackProject (..))-import Unit.Tricorder.Session.Helpers (cabalFixture, multiPackageCabalFs, multiPackageFs)+import Unit.Tricorder.Session.Helpers+    ( cabalFixture+    , multiPackageCabalFs+    , multiPackageFs+    , withHome+    , withProjectFiles+    )   test_CabalFile :: TestTree test_CabalFile =     testGroup         "CabalFile"-        [ testGroup "discoverCabalPackages" testDiscoverCabalPackages+        [ -- Discovery consults @$HOME/.cabal/config@, and @$HOME@ is process-global,+          -- so these must not run concurrently.+          dependentTestGroup "discoverCabalPackages" AllFinish testDiscoverCabalPackages         , testGroup "discoverStackPackages" testDiscoverStackPackages         , testGroup "readProjectFile" testReadProjectFile         ]@@ -39,80 +46,77 @@ -- otherwise the @.cabal@ files in the project root are used. Falls back -- further to @$HOME/.cabal/config@'s @packages:@ stanza if none of the -- project-root files exist.+--+-- Runs against real temporary directories; see 'runDiscovery'. testDiscoverCabalPackages :: [TestTree] testDiscoverCabalPackages =     [ testGroup         "when there is no cabal.project"         [ testCase "finds the .cabal files in the project root" do-            let actual =-                    runDiscovery (Map.singleton "/myapp.cabal" cabalFixture) []-                        $ discoverCabalPackages-            actual @?= Right ["/myapp.cabal"]+            actual <- runDiscovery (Map.singleton (rel "myapp.cabal") cabalFixture)+            actual @?= Right [rel "myapp.cabal"]         , testCase "returns no files when the root has no cabal file" do-            let actual = runDiscovery mempty [] discoverCabalPackages+            actual <- runDiscovery mempty             actual @?= Right []         ]     , testGroup         "when there is a multi-package cabal.project"         [ testCase "resolves each listed package to its .cabal (regression: was root-only)" do-            let actual = runDiscovery multiPackageFs [] discoverCabalPackages-            actual @?= Right ["/pkg-a/pkg-a.cabal", "/pkg-b/pkg-b.cabal"]+            actual <- runDiscovery multiPackageFs+            actual @?= Right [rel "pkg-a/pkg-a.cabal", rel "pkg-b/pkg-b.cabal"]         ]     , testGroup         "priority among cabal.project.local, cabal.project.freeze, and cabal.project"         [ testCase "prefers cabal.project.local over cabal.project" do-            let fs =-                    Map.fromList-                        [ ("/cabal.project.local", "packages: pkg-a\n")-                        , ("/cabal.project", "packages: pkg-b\n")+            actual <-+                runDiscovery+                    $ Map.fromList+                        [ (rel "cabal.project.local", "packages: pkg-a\n")+                        , (rel "cabal.project", "packages: pkg-b\n")                         ]                         `Map.union` multiPackageCabalFs-                actual = runDiscovery fs [] discoverCabalPackages-            actual @?= Right ["/pkg-a/pkg-a.cabal"]+            actual @?= Right [rel "pkg-a/pkg-a.cabal"]         , testCase "prefers cabal.project.freeze over cabal.project" do-            let fs =-                    Map.fromList-                        [ ("/cabal.project.freeze", "packages: pkg-a\n")-                        , ("/cabal.project", "packages: pkg-b\n")+            actual <-+                runDiscovery+                    $ Map.fromList+                        [ (rel "cabal.project.freeze", "packages: pkg-a\n")+                        , (rel "cabal.project", "packages: pkg-b\n")                         ]                         `Map.union` multiPackageCabalFs-                actual = runDiscovery fs [] discoverCabalPackages-            actual @?= Right ["/pkg-a/pkg-a.cabal"]+            actual @?= Right [rel "pkg-a/pkg-a.cabal"]         , testGroup             "when a higher-priority file lists no packages"             [ testCase "falls through to the next file in priority order" do-                let fs =-                        Map.fromList-                            [ ("/cabal.project.local", "tests: True\n")-                            , ("/cabal.project", "packages: pkg-b\n")+                actual <-+                    runDiscovery+                        $ Map.fromList+                            [ (rel "cabal.project.local", "tests: True\n")+                            , (rel "cabal.project", "packages: pkg-b\n")                             ]                             `Map.union` multiPackageCabalFs-                    actual = runDiscovery fs [] discoverCabalPackages-                actual @?= Right ["/pkg-b/pkg-b.cabal"]+                actual @?= Right [rel "pkg-b/pkg-b.cabal"]             ]         ]     , testGroup         "packages: entry resolution"         [ testCase "uses a direct .cabal path entry verbatim, without scanning a directory" do-            let fs = Map.singleton "/cabal.project" "packages: sub/foo.cabal\n"-                actual = runDiscovery fs [] discoverCabalPackages-            actual @?= Right ["/sub/foo.cabal"]+            actual <- runDiscovery $ Map.singleton (rel "cabal.project") "packages: sub/foo.cabal\n"+            actual @?= Right [rel "sub/foo.cabal"]         , testCase "expands a glob entry matching .cabal files directly" do-            let fs = Map.singleton "/cabal.project" "packages: */*.cabal\n"-                script = [Glob.NextGlobDir1 ["/pkg-a/pkg-a.cabal", "/pkg-b/pkg-b.cabal"]]-                actual = runDiscoveryGlob fs [] script discoverCabalPackages-            fromRight [] actual @?= ["/pkg-a/pkg-a.cabal", "/pkg-b/pkg-b.cabal"]+            actual <-+                runDiscovery+                    $ Map.singleton (rel "cabal.project") "packages: */*.cabal\n"+                        `Map.union` multiPackageCabalFs+            fromRight [] actual @?= [rel "pkg-a/pkg-a.cabal", rel "pkg-b/pkg-b.cabal"]         , testCase "expands a glob entry matching package directories" do-            let fs =-                    Map.singleton "/cabal.project" "packages: */\n"+            actual <-+                runDiscovery+                    $ Map.singleton (rel "cabal.project") "packages: */\n"                         `Map.union` multiPackageCabalFs-                script = [Glob.NextGlobDir1 ["/pkg-a", "/pkg-b"]]-                actual = runDiscoveryGlob fs [] script discoverCabalPackages-            fromRight [] actual @?= ["/pkg-a/pkg-a.cabal", "/pkg-b/pkg-b.cabal"]+            fromRight [] actual @?= [rel "pkg-a/pkg-a.cabal", rel "pkg-b/pkg-b.cabal"]         , testCase "returns no files when a glob entry matches nothing" do-            let fs = Map.singleton "/cabal.project" "packages: */*.cabal\n"-                script = [Glob.NextGlobDir1 []]-                actual = runDiscoveryGlob fs [] script discoverCabalPackages+            actual <- runDiscovery $ Map.singleton (rel "cabal.project") "packages: */*.cabal\n"             actual @?= Right []         ]     , testGroup@@ -120,22 +124,22 @@         [ testGroup             "when no cabal.project files exist"             [ testCase "uses $HOME/.cabal/config as a last-resort packages source" do-                let fs =-                        Map.singleton "/home/user/.cabal/config" "packages: pkg-a\n"+                actual <-+                    runDiscovery+                        $ Map.singleton (rel "home/.cabal/config") "packages: pkg-a\n"                             `Map.union` multiPackageCabalFs-                    actual = runDiscovery fs [("HOME", "/home/user")] discoverCabalPackages-                actual @?= Right ["/pkg-a/pkg-a.cabal"]+                actual @?= Right [rel "pkg-a/pkg-a.cabal"]             ]         , testGroup             "when $HOME/.cabal/config exists but lists no packages"             [ testCase "falls back to scanning the project root" do-                let fs =-                        Map.fromList-                            [ ("/home/user/.cabal/config", "")-                            , ("/myapp.cabal", cabalFixture)+                actual <-+                    runDiscovery+                        $ Map.fromList+                            [ (rel "home/.cabal/config", "")+                            , (rel "myapp.cabal", cabalFixture)                             ]-                    actual = runDiscovery fs [("HOME", "/home/user")] discoverCabalPackages-                actual @?= Right ["/myapp.cabal"]+                actual @?= Right [rel "myapp.cabal"]             ]         ]     , testGroup@@ -143,42 +147,53 @@         [ testGroup             "when package list is comma-separated"             [ testCase "parses package names correctly" do-                let fs =-                        Map.singleton "/cabal.project" "packages: pkg-a, pkg-b\n"+                actual <-+                    runDiscovery+                        $ Map.singleton (rel "cabal.project") "packages: pkg-a, pkg-b\n"                             `Map.union` multiPackageCabalFs-                    actual = runDiscovery fs [] discoverCabalPackages-                fromRight [] actual @?= ["/pkg-a/pkg-a.cabal", "/pkg-b/pkg-b.cabal"]+                fromRight [] actual @?= [rel "pkg-a/pkg-a.cabal", rel "pkg-b/pkg-b.cabal"]             ]         ]     ]   where-    pr = ProjectRoot "/"-    runDiscovery fs env = runDiscoveryGlob fs env []-    runDiscoveryGlob fs env script =-        runPureEff-            . Env.runConst env-            . evalState fs-            . FileSystem.runState-            . Glob.runScripted script-            . runReader pr+    -- Unchecked, for brevity: test inputs are known-good relative paths.+    rel :: FilePath -> Path.Relative+    rel = either error id . Path.fromFilePath  +-- | Materialise the given files in a temporary project root, run package+-- discovery there, and report the discovered paths relative to that root.+--+-- @$HOME@ is pointed at @home/@ inside the root, so a test can seed+-- @home/.cabal/config@ and tests that don't are unaffected by the real+-- @$HOME@.+runDiscovery :: Map Path.Relative ByteString -> IO (Either Text [Path.Relative])+runDiscovery files =+    withProjectFiles files \root -> do+        let pr = ProjectRoot root+        result <-+            withHome (root </> Path.relative @"home")+                $ Glob.runIO+                $ runReader pr discoverCabalPackages+        pure $ fmap (fmap (Path.makeRelative root)) result++ -- | Pins the discovery contract: with a @stack.yaml@, package paths come -- straight from its @packages:@ list, resolved against the project root. testDiscoverStackPackages :: [TestTree] testDiscoverStackPackages =     [ testCase "resolves each package path against the project root" do-        let actual = runStack (StackProject ["pkg-a", "pkg-b"]) discoverStackPackages-        actual @?= Right ["/pkg-a", "/pkg-b"]+        let actual = runStack (StackProject [Path.rel @"pkg-a", Path.rel @"pkg-b"]) discoverStackPackages+        actual @?= Right [Path.absolute @"/pkg-a", Path.absolute @"/pkg-b"]     , testCase "normalises resolved paths" do-        let actual = runStack (StackProject ["./pkg-a"]) discoverStackPackages-        actual @?= Right ["/pkg-a"]+        let actual = runStack (StackProject [Path.rel @"./pkg-a"]) discoverStackPackages+        actual @?= Right [Path.absolute @"/pkg-a"]     , testCase "returns no packages when the list is empty" do         let actual = runStack (StackProject []) discoverStackPackages         actual @?= Right []     ]   where-    pr = ProjectRoot "/"+    pr = ProjectRoot (Path.absolute @"/")     runStack result =         runPureEff             . runReader pr@@ -193,17 +208,17 @@     [ testGroup         "when the path is a directory"         [ testCase "reads the .cabal file inside it" do-            let actual = runRead multiPackageCabalFs $ readProjectFile "/pkg-a"-            actual @?= Right "/pkg-a/pkg-a.cabal"+            actual <- runRead multiPackageCabalFs+            actual @?= Right (Path.rel @"pkg-a/pkg-a.cabal")         , testCase "fails with the directory path when it contains no .cabal file" do-            let fs = Map.singleton "/pkg-a/package.yaml" "name: pkg-a\n"-                actual = runRead fs $ readProjectFile "/pkg-a"-            actual @?= Left "/pkg-a"+            actual <- runRead $ Map.singleton (Path.rel @"pkg-a/package.yaml") "name: pkg-a\n"+            actual @?= Left (Path.rel @"pkg-a")         ]     ]   where-    runRead fs =-        fmap (.projectFilePath)-            . runPureEff-            . evalState fs-            . FileSystem.runState+    -- Reads @pkg-a@ in a temporary project root, reporting paths relative to it.+    runRead files =+        withProjectFiles files \root -> do+            result <- readProjectFile $ root </> Path.rel @"pkg-a"+            pure+                $ bimap (Path.makeRelative root) (Path.makeRelative root . (.projectFilePath)) result
test/Unit/Tricorder/Session/Helpers.hs view
@@ -9,12 +9,24 @@     , gpdFixture     , cabalFixture     , gpd+    , withProjectFiles+    , withHome     ) where +import Atelier.FileSystem.Path ((</>))+import Control.Exception (bracket) import Distribution.PackageDescription (GenericPackageDescription) import Distribution.PackageDescription.Parsec (parseGenericPackageDescriptionMaybe)+import Effectful (IOE, runEff)+import Effectful.Exception (finally)+import Effectful.FileSystem (FileSystem, runFileSystem)+import System.Environment (lookupEnv, setEnv, unsetEnv)+import System.Posix.Temp (mkdtemp) +import Atelier.FileSystem.Directory qualified as Directory+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map import Data.Text qualified as T @@ -30,7 +42,8 @@ multiCabalFiles :: [CabalFile] multiCabalFiles =     uncurry CabalFile-        . second+        . bimap+            (Path.absolute @"/" </>)             ( fromMaybe (error "multiCabalFiles failed to parse")                 . parseGenericPackageDescriptionMaybe             )@@ -39,19 +52,19 @@  -- | An in-memory project root with a @cabal.project@ listing two packages, -- each in its own subdirectory with a library and a test suite.-multiPackageFs :: Map FilePath ByteString+multiPackageFs :: Map Path.Relative ByteString multiPackageFs =     Map.fromList-        [ ("/cabal.project", "packages:\n  pkg-a\n  pkg-b\n\ntests: True\n")+        [ (Path.rel @"cabal.project", "packages:\n  pkg-a\n  pkg-b\n\ntests: True\n")         ]         `Map.union` multiPackageCabalFs  -multiPackageCabalFs :: Map FilePath ByteString+multiPackageCabalFs :: Map Path.Relative ByteString multiPackageCabalFs =     Map.fromList-        [ ("/pkg-a/pkg-a.cabal", libTestCabal "pkg-a")-        , ("/pkg-b/pkg-b.cabal", libTestCabal "pkg-b")+        [ (Path.rel @"pkg-a/pkg-a.cabal", libTestCabal "pkg-a")+        , (Path.rel @"pkg-b/pkg-b.cabal", libTestCabal "pkg-b")         ]  @@ -127,7 +140,7 @@   singleCabalFile :: [CabalFile]-singleCabalFile = [CabalFile "/myapp.cabal" gpdFixture]+singleCabalFile = [CabalFile (Path.absolute @"/myapp.cabal") gpdFixture]   gpdFixture :: GenericPackageDescription@@ -176,3 +189,44 @@     \  hs-source-dirs: bench\n\     \  build-depends: base\n\     \  default-language: Haskell2010\n"+++-- | Seed a fresh temporary directory with the given files (paths relative to+-- it, parent directories created as needed), run the action with that+-- directory as its project root, and delete the directory afterwards.+--+-- 'Effectful.FileSystem' only has a real-IO interpreter, so tests that need a+-- particular file layout have to materialise it on disk.+withProjectFiles+    :: Map Path.Relative ByteString+    -> (Path.Absolute -> Eff '[FileSystem, IOE] a)+    -> IO a+withProjectFiles files act =+    bracket (mkAbsolute <$> mkdtemp "/tmp/tricorder-test-") cleanup \root -> run do+        for_ (Map.toList files) \(path, content) -> do+            let file = root </> path+            Directory.createIfMissing True (Path.takeDirectory file)+            File.write file content+        act root+  where+    run = runEff . runFileSystem+    cleanup = run . Directory.removeRecursive+    mkAbsolute = either error id . Path.fromFilePath @Path.Absolute+++-- | Run an action with @$HOME@ pointing at the given directory (and+-- @$XDG_CACHE_HOME@ unset, so XDG lookups fall back to @$HOME/.cache@),+-- restoring the previous values afterwards. These are process-global, so tests+-- using this must not run concurrently with each other (see+-- 'dependentTestGroup').+withHome :: (IOE :> es) => Path.Absolute -> Eff es a -> Eff es a+withHome home act = do+    oldHome <- liftIO $ lookupEnv "HOME"+    oldXdgCache <- liftIO $ lookupEnv "XDG_CACHE_HOME"+    liftIO $ setEnv "HOME" (Path.toFilePath home)+    liftIO $ unsetEnv "XDG_CACHE_HOME"+    act `finally` liftIO do+        restore "HOME" oldHome+        restore "XDG_CACHE_HOME" oldXdgCache+  where+    restore name = maybe (unsetEnv name) (setEnv name)
test/Unit/Tricorder/Session/ReplSpec.hs view
@@ -1,16 +1,15 @@ module Unit.Tricorder.Session.ReplSpec (test_Repl) where -import Atelier.Effects.FileSystem (FileSystem)-import Effectful (runPureEff)-import Effectful.State.Static.Shared (State, evalState)+import Atelier.FileSystem.Path ((</>)) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (testCase, (@?=)) -import Atelier.Effects.FileSystem qualified as FileSystem+import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.Repl (Repl (..), resolveRepl)+import Unit.Tricorder.Session.Helpers (withProjectFiles)   test_Repl :: TestTree@@ -24,30 +23,45 @@ testResolveRepl :: [TestTree] testResolveRepl =     [ testCase "resolves Stack for a single-package stack.yaml" do-        withFiles [("/stack.yaml", "")] (resolveRepl pr) @?= Stack+        resolve [(Path.rel @"stack.yaml", "")]+            >>= (@?= Stack)     , testCase "resolves StackMulti for a multi-package stack.yaml" do-        withFiles-            [("/stack.yaml", "packages:\n  - foo\n  - bar\n")]-            (resolveRepl pr)-            @?= StackMulti+        resolve [(Path.rel @"stack.yaml", "packages:\n  - foo\n  - bar\n")]+            >>= (@?= StackMulti)     , testCase "resolves Cabal when there is a cabal.project file" do-        withFiles [("/cabal.project", "")] (resolveRepl pr) @?= Cabal+        resolve [(Path.rel @"cabal.project", "")]+            >>= (@?= Cabal)     , testCase "resolves Cabal when there is at least one *.cabal file" do-        withFiles [("/foo.cabal", "")] (resolveRepl pr) @?= Cabal+        resolve [(Path.rel @"foo.cabal", "")]+            >>= (@?= Cabal)     , testCase "prefers Stack over Cabal when both are present" do-        withFiles [("/stack.yaml", ""), ("/cabal.project", "")] (resolveRepl pr) @?= Stack+        resolve+            [ (Path.rel @"stack.yaml", "")+            , (Path.rel @"cabal.project", "")+            ]+            >>= (@?= Stack)+    , testCase "finds stack.yaml in an ancestor of the project root" do+        resolveAt+            (Path.rel @"pkg")+            [ (Path.rel @"stack.yaml", "packages:\n  - foo\n  - bar\n")+            , (Path.rel @"pkg/README.md", "")+            ]+            >>= (@?= StackMulti)     , testCase "falls back to Cabal when there are no project files at all" do-        withFiles [] (resolveRepl pr) @?= Cabal+        resolve []+            >>= (@?= Cabal)     ]  --- | Run a 'FileSystem'-using computation against a faked in-memory--- filesystem seeded with the given files (content is irrelevant except for--- @stack.yaml@, which is parsed for its @packages@ key).-withFiles :: [(FilePath, ByteString)] -> Eff '[FileSystem, State (Map FilePath ByteString)] a -> a-withFiles files action =-    runPureEff $ evalState (Map.fromList files) $ FileSystem.runState action+-- | Resolve the 'Repl' of a temporary project root seeded with the given+-- files (content is irrelevant except for @stack.yaml@, which is parsed for+-- its @packages@ key).+resolve :: [(Path.Relative, ByteString)] -> IO Repl+resolve files = withProjectFiles (Map.fromList files) (resolveRepl . ProjectRoot)  -pr :: ProjectRoot-pr = ProjectRoot "/"+-- | Like 'resolve', but with the project root at the given subdirectory of the+-- temporary directory the files are seeded in.+resolveAt :: Path.Relative -> [(Path.Relative, ByteString)] -> IO Repl+resolveAt sub files =+    withProjectFiles (Map.fromList files) \root -> resolveRepl $ ProjectRoot $ root </> sub
+ test/Unit/Tricorder/Session/StackProjectSpec.hs view
@@ -0,0 +1,31 @@+module Unit.Tricorder.Session.StackProjectSpec (test_StackProject) where++import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (testCase, (@?=))++import Atelier.FileSystem.Path qualified as Path+import Data.Yaml qualified as Yaml++import Tricorder.Session.StackProject (StackProject (..))+++test_StackProject :: TestTree+test_StackProject =+    testGroup+        "StackProject"+        [ testCase "defaults packages to [\".\"] when the key is absent" do+            decode "resolver: lts-24.0\n"+                @?= Right (StackProject [Path.rel @"."])+        , testCase "defaults packages to [\".\"] for an empty document" do+            decode "{}\n"+                @?= Right (StackProject [Path.rel @"."])+        , testCase "reads an explicit packages list" do+            decode "packages:\n  - foo\n  - bar\n"+                @?= Right (StackProject [Path.rel @"foo", Path.rel @"bar"])+        , testCase "keeps an explicitly empty packages list" do+            decode "packages: []\n"+                @?= Right (StackProject [])+        ]+  where+    decode :: ByteString -> Either String StackProject+    decode = first show . Yaml.decodeEither'
test/Unit/Tricorder/Session/Stage/Build/CommandSpec.hs view
@@ -1,24 +1,21 @@ module Unit.Tricorder.Session.Stage.Build.CommandSpec (test_Command) where -import Atelier.Effects.FileSystem (FileSystem) import Data.Default (def)-import Effectful (runPureEff)-import Effectful.State.Static.Shared (State, evalState) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (testCase, (@?=)) -import Atelier.Effects.FileSystem qualified as FileSystem+import Atelier.FileSystem.Path qualified as Path import Data.Map.Strict qualified as Map -import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.Command.RenderedCommand (RenderedCommand (..)) import Tricorder.Session.CommandConfig (CommandConfig (..)) import Tricorder.Session.CommandTemplate (CommandTemplate (..), targetsPlaceholder) import Tricorder.Session.Config (Config (..)) import Tricorder.Session.Repl (Repl (..), resolveRepl)-import Tricorder.Session.Stage (Stage (..)) import Tricorder.Session.Stage.Build.Command (render, resolve) import Tricorder.Session.Target (Target)+import Unit.Tricorder.Session.Helpers (withProjectFiles)  import Tricorder.Session.Config qualified as Config import Tricorder.Session.Target qualified as Target@@ -77,48 +74,46 @@     [ testGroup         "explicit targets"         [ testCase "spell them out verbatim" do-            renderBuildFor [("/cabal.project", "")] cfg0 (Target.parse <$> ["lib:foo"])-                @?= "cabal repl --enable-multi-repl --builddir /replbuild lib:foo"+            renderBuildFor [(Path.rel @"cabal.project", "")] cfg0 (Target.parse <$> ["lib:foo"])+                >>= (@?= "cabal repl --enable-multi-repl --builddir /replbuild lib:foo")         ]     , testGroup         "no command or targets configured"         [ testGroup             "and there is a cabal.project file"             [ testCase "uses cabal 'all'" do-                renderBuildFor [("/cabal.project", "")] cfg0 []-                    @?= "cabal repl --enable-multi-repl --builddir /replbuild all"+                renderBuildFor [(Path.rel @"cabal.project", "")] cfg0 []+                    >>= (@?= "cabal repl --enable-multi-repl --builddir /replbuild all")             ]         , testGroup             "and there is at least one *.cabal file"             [ testCase "uses cabal 'all'" do-                renderBuildFor [("/foo.cabal", "")] cfg0 []-                    @?= "cabal repl --enable-multi-repl --builddir /replbuild all"+                renderBuildFor [(Path.rel @"foo.cabal", "")] cfg0 []+                    >>= (@?= "cabal repl --enable-multi-repl --builddir /replbuild all")             ]         , testGroup             "and there is a stack.yaml file"             [ testCase "uses stack ghci with 'all'" do-                renderBuildFor [("/stack.yaml", "")] cfg0 []-                    @?= "stack ghci all"+                renderBuildFor [(Path.rel @"stack.yaml", "")] cfg0 [] >>= (@?= "stack ghci all")             ]         , testGroup             "and there is both a stack.yaml and a cabal.project file"             [ testCase "prefers stack ghci over cabal" do-                renderBuildFor [("/stack.yaml", ""), ("/cabal.project", "")] cfg0 []-                    @?= "stack ghci all"+                renderBuildFor [(Path.rel @"stack.yaml", ""), (Path.rel @"cabal.project", "")] cfg0 []+                    >>= (@?= "stack ghci all")             ]         , testGroup             "but there are no project files"             [ testCase "uses default cabal repl with 'all'" do-                renderBuildFor [] cfg0 []-                    @?= "cabal repl --builddir /replbuild all"+                renderBuildFor [] cfg0 [] >>= (@?= "cabal repl --builddir /replbuild all")             ]         ]     , testGroup         "build.extra_auto_arguments"         [ testCase "is appended after the rendered automatically resolved template" do             let cfg = cfg0 {build = cfg0.build {extraAutoArguments = ["--extra-flag"]}}-            renderBuildFor [("/cabal.project", "")] cfg (Target.parse <$> ["lib:foo"])-                @?= "cabal repl --enable-multi-repl --builddir /replbuild lib:foo --extra-flag"+            renderBuildFor [(Path.rel @"cabal.project", "")] cfg (Target.parse <$> ["lib:foo"])+                >>= (@?= "cabal repl --enable-multi-repl --builddir /replbuild lib:foo --extra-flag")         , testCase "is ignored when build.command_template is set" do             let cfg =                     cfg0@@ -128,43 +123,24 @@                                 , extraAutoArguments = ["--extra-flag"]                                 }                         }-            renderBuildFor [("/cabal.project", "")] cfg (Target.parse <$> ["lib:foo"])-                @?= "cabal repl lib:foo"+            renderBuildFor [(Path.rel @"cabal.project", "")] cfg (Target.parse <$> ["lib:foo"])+                >>= (@?= "cabal repl lib:foo")         ]     ]  --- | Resolve and fully render the build command against a faked filesystem —--- the composition 'Tricorder.Session.loadSession' and 'Tricorder.Daemon.Core'--- perform between them (resolve a 'CommandTemplate' plus its target list,--- then 'renderBuild' the two together).-renderBuildFor :: [(FilePath, ByteString)] -> Config -> [Target] -> Text+-- | Resolve and fully render the build command against a temporary project+-- root seeded with the given files — the composition+-- 'Tricorder.Session.loadSession' and 'Tricorder.Daemon.Core' perform between+-- them (resolve a 'CommandTemplate' plus its target list, then 'renderBuild'+-- the two together).+renderBuildFor :: [(Path.Relative, ByteString)] -> Config -> [Target] -> IO Text renderBuildFor files cfg targets =-    (uncurry render $ withFiles files $ resolveBuild cfg targets).getRenderedCommand----- | Run a 'FileSystem'-using computation against a faked in-memory--- filesystem seeded with the given files (content is irrelevant except for--- @stack.yaml@, which is parsed for its @packages@ key).-withFiles :: [(FilePath, ByteString)] -> Eff '[FileSystem, State (Map FilePath ByteString)] a -> a-withFiles files action =-    runPureEff $ evalState (Map.fromList files) $ FileSystem.runState action+    withProjectFiles (Map.fromList files) \root -> do+        let pr = ProjectRoot root+        repl <- resolveRepl pr+        (.getRenderedCommand) . uncurry render <$> resolve pr cfg repl targets   cfg0 :: Config cfg0 = def {Config.replBuildDir = "/replbuild"}----- | Resolve 'Repl' from the faked filesystem, then resolve the build--- command from it — mirrors how 'Tricorder.Session.loadSession' chains the--- two steps.-resolveBuild-    :: (FileSystem :> es)-    => Config -> [Target] -> Eff es (CommandTemplate 'Build, [Target])-resolveBuild cfg targets = do-    repl <- resolveRepl pr-    resolve pr cfg repl targets---pr :: ProjectRoot-pr = ProjectRoot "/"
test/Unit/Tricorder/Session/TargetSpec.hs view
@@ -5,6 +5,8 @@ import Test.Tasty.HUnit (assertBool, testCase, (@?=)) import Prelude hiding (compare) +import Atelier.FileSystem.Path qualified as Path+ import Tricorder.Session.CabalFile (CabalFile (..)) import Tricorder.Session.Target     ( ComponentKind (..)@@ -108,7 +110,7 @@                     ]         , testCase "sorts a library exposing a custom Prelude last" do             let cabalFile =-                    CabalFile "/myprelude.cabal"+                    CabalFile (Path.absolute @"/myprelude.cabal")                         $ fromMaybe (error "libWithPreludeCabal failed to parse")                         $ parseGenericPackageDescriptionMaybe (libWithPreludeCabal "myprelude")             let actual = resolve [cabalFile] []@@ -264,6 +266,6 @@     ]   where     preludeCF =-        CabalFile "/myprelude.cabal"+        CabalFile (Path.absolute @"/myprelude.cabal")             $ fromMaybe (error "libWithPreludeCabal failed to parse")             $ parseGenericPackageDescriptionMaybe (libWithPreludeCabal "myprelude")
test/Unit/Tricorder/Session/WatchDirsSpec.hs view
@@ -4,7 +4,9 @@ import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (testCase, (@?=)) -import Tricorder.Runtime (ProjectRoot (..))+import Atelier.FileSystem.Path qualified as Path++import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.Config (Config (..)) import Tricorder.Session.Target (ComponentKind (..), Target (..)) import Tricorder.Session.WatchDirs (WatchDirs (..), sourceDirsForTarget)@@ -28,50 +30,63 @@     [ testGroup         "when watch_dirs is set in config"         [ testCase "uses config dirs relative to project root" do-            let WatchDirs actual =+            let actual =                     WatchDirs.resolve pr [] def {watchDirs = ["src", "test"]} []-            actual @?= ["/src", "/test"]+            actual+                @?= Right (WatchDirs [Path.absolute @"/src", Path.absolute @"/test"])         ]     , testGroup         "when watch_dirs is not set"         [ testCase "falls back to [\".\"] when targets list is empty" do-            let WatchDirs actual = WatchDirs.resolve pr [] def []-            actual @?= ["."]+            let actual = WatchDirs.resolve pr [] def []+            actual+                @?= Right (WatchDirs [Path.absolute @"/"])         , testCase "infers source dirs from resolved targets" do-            let WatchDirs actual =+            let actual =                     WatchDirs.resolve pr singleCabalFile def (mkTargets ["lib:myapp", "test:myapp-test"])-            actual @?= ["/src", "/test"]+            actual+                @?= Right (WatchDirs [Path.absolute @"/src", Path.absolute @"/test"])         , testCase "falls back to [\".\"] when there are no cabal files" do-            let WatchDirs actual =+            let actual =                     WatchDirs.resolve pr [] def (mkTargets ["lib:myapp"])-            actual @?= ["."]+            actual+                @?= Right (WatchDirs [Path.absolute @"/"])         , -- Sharp edge: an unparseable .cabal yields no source dirs, so resolution           -- falls back to watching the whole project root. This pins the current           -- behavior; if it ever changes to something narrower, update this test.           testCase "falls back to [\".\"] when no cabal files are found or parsed" do-            let WatchDirs actual =+            let actual =                     WatchDirs.resolve pr [] def (mkTargets ["lib:myapp"])-            actual @?= ["."]+            actual+                @?= Right (WatchDirs [Path.absolute @"/"])         ]     , testGroup         "when the project is a multi-package cabal.project"         [ testCase "infers per-package source dirs, scoped to each package's directory" do-            let WatchDirs actual =+            let actual =                     WatchDirs.resolve                         pr                         multiCabalFiles                         def                         (mkTargets ["lib:pkg-a", "test:pkg-a-test", "lib:pkg-b", "test:pkg-b-test"])             actual-                @?= ["/pkg-a/src", "/pkg-a/test", "/pkg-b/src", "/pkg-b/test"]+                @?= Right+                    ( WatchDirs+                        [ Path.absolute @"/pkg-a/src"+                        , Path.absolute @"/pkg-a/test"+                        , Path.absolute @"/pkg-b/src"+                        , Path.absolute @"/pkg-b/test"+                        ]+                    )         , testCase "scopes a bare package-name target to that package, ignoring siblings" do-            let WatchDirs actual =+            let actual =                     WatchDirs.resolve pr multiCabalFiles def (mkTargets ["pkg-a"])-            actual @?= ["/pkg-a/src", "/pkg-a/test"]+            actual+                @?= Right (WatchDirs [Path.absolute @"/pkg-a/src", Path.absolute @"/pkg-a/test"])         ]     ]   where-    pr = ProjectRoot "/"+    pr = ProjectRoot (Path.absolute @"/")   -- | These exercise the 'Target' -> dirs resolution directly with constructed@@ -83,82 +98,93 @@         [ testGroup             "when the name is empty"             [ testCase "returns the main library source dirs" do-                sourceDirsForTarget gpd (Qualified Lib "") @?= ["src"]+                sourceDirsForTarget gpd (Qualified Lib "") @?= Right [Path.Relative (Path.rel @"src")]             ]         , testGroup             "when the name matches the package name"             [ testCase "returns the main library source dirs" do-                sourceDirsForTarget gpd (Qualified Lib "myapp") @?= ["src"]+                sourceDirsForTarget gpd (Qualified Lib "myapp") @?= Right [Path.Relative (Path.rel @"src")]             ]         , testGroup             "when the name matches a sub-library"             [ testCase "returns the sub-library source dirs" do-                sourceDirsForTarget gpd (Qualified Lib "myapp-utils") @?= ["utils"]+                sourceDirsForTarget gpd (Qualified Lib "myapp-utils") @?= Right [Path.Relative (Path.rel @"utils")]             ]         , testGroup             "when the sub-library is unknown"             [ testCase "returns an empty list" do-                sourceDirsForTarget gpd (Qualified Lib "nonexistent") @?= []+                sourceDirsForTarget gpd (Qualified Lib "nonexistent") @?= Right []             ]         ]     , testGroup         "Qualified FLib"         [ testCase "returns the foreign-library source dirs" do-            sourceDirsForTarget gpd (Qualified FLib "myapp-flib") @?= ["flib"]+            sourceDirsForTarget gpd (Qualified FLib "myapp-flib") @?= Right [Path.Relative (Path.rel @"flib")]         ]     , testGroup         "Qualified Exe"         [ testCase "returns the executable source dirs" do-            sourceDirsForTarget gpd (Qualified Exe "myapp-exe") @?= ["app"]+            sourceDirsForTarget gpd (Qualified Exe "myapp-exe") @?= Right [Path.Relative (Path.rel @"app")]         ]     , testGroup         "Qualified Test"         [ testCase "returns the test suite source dirs" do-            sourceDirsForTarget gpd (Qualified Test "myapp-test") @?= ["test"]+            sourceDirsForTarget gpd (Qualified Test "myapp-test") @?= Right [Path.Relative (Path.rel @"test")]         ]     , testGroup         "Qualified Bench"         [ testCase "returns the benchmark source dirs" do-            sourceDirsForTarget gpd (Qualified Bench "myapp-bench") @?= ["bench"]+            sourceDirsForTarget gpd (Qualified Bench "myapp-bench")+                @?= Right [Path.Relative (Path.rel @"bench")]         ]     , testGroup         "Bare (package name)"         [ testCase "returns every component's source dirs" do-            sourceDirsForTarget gpd (Bare "myapp") @?= ["src", "utils", "flib", "app", "test", "bench"]+            sourceDirsForTarget gpd (Bare "myapp")+                @?= Right+                    [ Path.Relative (Path.rel @"src")+                    , Path.Relative (Path.rel @"utils")+                    , Path.Relative (Path.rel @"flib")+                    , Path.Relative (Path.rel @"app")+                    , Path.Relative (Path.rel @"test")+                    , Path.Relative (Path.rel @"bench")+                    ]         ]     , testGroup         "Bare (component name)"         [ testGroup             "when it names a sub-library"             [ testCase "returns the sub-library source dirs" do-                sourceDirsForTarget gpd (Bare "myapp-utils") @?= ["utils"]+                sourceDirsForTarget gpd (Bare "myapp-utils") @?= Right [Path.Relative (Path.rel @"utils")]             ]         , testGroup             "when it names an executable"             [ testCase "returns the executable source dirs" do-                sourceDirsForTarget gpd (Bare "myapp-exe") @?= ["app"]+                sourceDirsForTarget gpd (Bare "myapp-exe") @?= Right [Path.Relative (Path.rel @"app")]             ]         , testGroup             "when it names a test suite"             [ testCase "returns the test suite source dirs" do-                sourceDirsForTarget gpd (Bare "myapp-test") @?= ["test"]+                sourceDirsForTarget gpd (Bare "myapp-test") @?= Right [Path.Relative (Path.rel @"test")]             ]         , testGroup             "when it matches no component"             [ testCase "returns an empty list" do-                sourceDirsForTarget gpd (Bare "unknown") @?= []+                sourceDirsForTarget gpd (Bare "unknown") @?= Right []             ]         ]     , testGroup         "Unrecognized"         [ testCase "matches an aliased kind prefix by trailing name" do-            sourceDirsForTarget gpd (Unrecognized "executable:myapp-exe") @?= ["app"]+            sourceDirsForTarget gpd (Unrecognized "executable:myapp-exe")+                @?= Right [Path.Relative (Path.rel @"app")]         , testCase "matches a case-variant kind prefix by trailing name" do-            sourceDirsForTarget gpd (Unrecognized "Test-Suite:myapp-test") @?= ["test"]+            sourceDirsForTarget gpd (Unrecognized "Test-Suite:myapp-test")+                @?= Right [Path.Relative (Path.rel @"test")]         , testCase "matches the main library when the trailing name is the package name" do-            sourceDirsForTarget gpd (Unrecognized "library:myapp") @?= ["src"]+            sourceDirsForTarget gpd (Unrecognized "library:myapp") @?= Right [Path.Relative (Path.rel @"src")]         , testCase "returns an empty list when the trailing name matches no component" do-            sourceDirsForTarget gpd (Unrecognized "bogus:x") @?= []+            sourceDirsForTarget gpd (Unrecognized "bogus:x") @?= Right []         ]     ] 
test/Unit/Tricorder/SessionSpec.hs view
@@ -3,24 +3,22 @@ import Atelier.Effects.Log (Message (..), Severity (..)) import Data.Aeson (object, (.=)) import Distribution.PackageDescription.Parsec (parseGenericPackageDescriptionMaybe)-import Effectful (runPureEff) import Effectful.Reader.Static (runReader)-import Effectful.State.Static.Shared (evalState) import Effectful.Writer.Static.Shared (execWriter) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (assertFailure, testCase, (@?), (@?=)) -import Atelier.Effects.FileSystem qualified as FileSystem import Atelier.Effects.Input qualified as Input import Atelier.Effects.Log qualified as Log+import Atelier.FileSystem.Path qualified as Path import Data.Aeson qualified as Aeson import Data.Text qualified as T  import Tricorder.Config.LoadedConfig (LoadedConfig (..))-import Tricorder.Runtime (ProjectRoot (..))+import Tricorder.Runtime.ProjectRoot (ProjectRoot (..)) import Tricorder.Session.CabalFile (CabalFile (..)) import Tricorder.Session.IdleTimeout (IdleTimeout (..))-import Unit.Tricorder.Session.Helpers (libWithPreludeCabal, preludeOnlyLibCabal)+import Unit.Tricorder.Session.Helpers (libWithPreludeCabal, preludeOnlyLibCabal, withProjectFiles)  import Tricorder.Config qualified import Tricorder.Session qualified as Session@@ -43,10 +41,10 @@         [ testGroup             "when every resolved target exposes a custom Prelude module"             [ testCase "logs one message" do-                let msgs = captureSessionLogs [preludeOnlyCF]+                msgs <- captureSessionLogs [preludeOnlyCF]                 length msgs @?= 1             , testCase "emits a WARN" do-                let msgs = (\m -> (m.severity, m.text)) <$> captureSessionLogs [preludeOnlyCF]+                msgs <- fmap (\m -> (m.severity, m.text)) <$> captureSessionLogs [preludeOnlyCF]                 case msgs of                     [(sev, msg)] -> do                         sev @?= WARN@@ -59,34 +57,33 @@             "when not every resolved target exposes a custom Prelude module"             [ testCase "does not emit a WARN" do                 -- libWithPreludeCabal has both a lib (custom Prelude) and an exe (no Prelude)-                let msgs = captureSessionLogs [mixedCF]+                msgs <- captureSessionLogs [mixedCF]                 any (\m -> m.severity == WARN) msgs @?= False             ]         , testCase "does not emit a WARN when there are no resolved targets" do-            any (\m -> m.severity == WARN) (captureSessionLogs []) @?= False+            msgs <- captureSessionLogs []+            any (\m -> m.severity == WARN) msgs @?= False         ]   where     preludeOnlyCF =-        CabalFile "/p.cabal"+        CabalFile (Path.absolute @"/p.cabal")             $ fromMaybe (error "preludeOnlyLibCabal failed to parse")             $ parseGenericPackageDescriptionMaybe (preludeOnlyLibCabal "p")     mixedCF =-        CabalFile "/mixed.cabal"+        CabalFile (Path.absolute @"/mixed.cabal")             $ fromMaybe (error "libWithPreludeCabal failed to parse")             $ parseGenericPackageDescriptionMaybe (libWithPreludeCabal "mixed")     captureSessionLogs = captureSessionLogs' $ Aeson.Object mempty     captureSessionLogs' cfg cabalFiles =-        filter (\m -> m.severity /= DEBUG)-            . runPureEff-            . execWriter @[Message]-            . Log.runWriter-            . evalState @(Map FilePath ByteString) mempty-            . FileSystem.runState-            . Input.withConst cabalFiles-            . runReader (ProjectRoot "/")-            . Input.withConst (LoadedConfig $ toStrict $ Aeson.encode cfg)-            . Tricorder.Config.asInput-            $ Session.load+        withProjectFiles mempty \root ->+            fmap (filter (\m -> m.severity /= DEBUG))+                . execWriter @[Message]+                . Log.runWriter+                . Input.withConst cabalFiles+                . runReader (ProjectRoot root)+                . Input.withConst (LoadedConfig $ toStrict $ Aeson.encode cfg)+                . Tricorder.Config.asInput+                $ Session.load   testMissingTargetPlaceholder :: TestTree@@ -97,40 +94,43 @@             "test.command_template"             [ testCase "emits a WARN when it has no {target} placeholder" do                 let cfg = sessionCfg ["test" .= object ["command_template" .= ("cabal repl test:foo" :: Text)]]-                any (\m -> m.severity == WARN) (captureLogsFor cfg) @?= True+                logs <- captureLogsFor cfg+                any (\m -> m.severity == WARN) logs @?= True             , testCase "does not emit a WARN when it has the {target} placeholder" do                 let cfg = sessionCfg ["test" .= object ["command_template" .= ("cabal repl {target}" :: Text)]]-                any (\m -> m.severity == WARN) (captureLogsFor cfg) @?= False+                logs <- captureLogsFor cfg+                any (\m -> m.severity == WARN) logs @?= False             ]         , testGroup             "eval.command_template"             [ testCase "emits a WARN when it has no {target} placeholder" do                 let cfg = sessionCfg ["eval" .= object ["command_template" .= ("cabal repl Tricorder.Foo" :: Text)]]-                any (\m -> m.severity == WARN) (captureLogsFor cfg) @?= True+                logs <- captureLogsFor cfg+                any (\m -> m.severity == WARN) logs @?= True             , testCase "does not emit a WARN when it has the {target} placeholder" do                 let cfg = sessionCfg ["eval" .= object ["command_template" .= ("cabal repl {target}" :: Text)]]-                any (\m -> m.severity == WARN) (captureLogsFor cfg) @?= False+                logs <- captureLogsFor cfg+                any (\m -> m.severity == WARN) logs @?= False             ]         , testGroup             "build.command_template"             [ testCase "does not emit a WARN when it has no {targets} placeholder" do                 let cfg = sessionCfg ["build" .= object ["command_template" .= ("cabal repl lib:foo" :: Text)]]-                any (\m -> m.severity == WARN) (captureLogsFor cfg) @?= False+                logs <- captureLogsFor cfg+                any (\m -> m.severity == WARN) logs @?= False             ]         ]   where     sessionCfg session = object ["session" .= object session]     captureLogsFor cfg =-        runPureEff-            . execWriter @[Message]-            . Log.runWriter-            . evalState @(Map FilePath ByteString) mempty-            . FileSystem.runState-            . Input.withConst ([] :: [CabalFile])-            . runReader (ProjectRoot "/")-            . Input.withConst (LoadedConfig $ toStrict $ Aeson.encode cfg)-            . Tricorder.Config.asInput-            $ Session.load+        withProjectFiles mempty \root ->+            execWriter @[Message]+                . Log.runWriter+                . Input.withConst ([] :: [CabalFile])+                . runReader (ProjectRoot root)+                . Input.withConst (LoadedConfig $ toStrict $ Aeson.encode cfg)+                . Tricorder.Config.asInput+                $ Session.load   testIdleTimeout :: TestTree@@ -138,19 +138,19 @@     testGroup         "loadSession idleTimeout"         [ testCase "defaults to 300 seconds when unset" do-            (.idleTimeout) <$> loadSessionWith (Aeson.Object mempty) @?= Right (IdleTimeout 300)+            loaded <- loadSessionWith (Aeson.Object mempty)+            (.idleTimeout) <$> loaded @?= Right (IdleTimeout 300)         , testCase "reads idle_timeout_seconds from the session config" do             let cfg = object ["session" .= object ["idle_timeout_seconds" .= (5 :: Int)]]-            (.idleTimeout) <$> (loadSessionWith cfg) @?= Right (IdleTimeout 5)+            loaded <- loadSessionWith cfg+            (.idleTimeout) <$> loaded @?= Right (IdleTimeout 5)         ]   where     loadSessionWith cfg =-        runPureEff-            . Log.runNoOp-            . evalState @(Map FilePath ByteString) mempty-            . FileSystem.runState-            . Input.withConst ([] :: [CabalFile])-            . runReader (ProjectRoot "/")-            . Input.withConst (LoadedConfig $ toStrict $ Aeson.encode cfg)-            . Tricorder.Config.asInput-            $ Session.load+        withProjectFiles mempty \root ->+            Log.runNoOp+                . Input.withConst ([] :: [CabalFile])+                . runReader (ProjectRoot root)+                . Input.withConst (LoadedConfig $ toStrict $ Aeson.encode cfg)+                . Tricorder.Config.asInput+                $ Session.load
test/Unit/Tricorder/SocketSpec.hs view
@@ -1,15 +1,16 @@ module Unit.Tricorder.SocketSpec (test_Socket) where -import Atelier.Effects.File (File)-import Atelier.Effects.FileSystem (FileSystem)+import Atelier.Effects.Handles (Handles) import Effectful (IOE, runEff) import Effectful.Exception (trySync)+import Effectful.FileSystem (FileSystem, runFileSystem) import System.IO (hClose, hGetLine, openFile, writeFile) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit (testCase, (@?=)) -import Atelier.Effects.File qualified as File-import Atelier.Effects.FileSystem qualified as FileSystem+import Atelier.Effects.Handles qualified as Handles+import Atelier.FileSystem.File qualified as File+import Atelier.FileSystem.Path qualified as Path  import Tricorder.Socket.Client (isDaemonReady) import Tricorder.Socket.UnixSocket (SocketScript (..), UnixSocket)@@ -39,7 +40,7 @@             writeFile tmpPath "hello from test\n"             h <- liftIO $ openFile tmpPath ReadMode             line <- runScripted [NextAccept h] $ do-                sock <- UnixSocket.bind "/"+                sock <- UnixSocket.bind (Path.absolute @"/")                 h' <- UnixSocket.accept sock                 liftIO $ hGetLine h'             liftIO $ hClose h@@ -57,15 +58,15 @@     [ testCase "returns False when nothing is listening on the path" do         -- A connect to a non-existent socket must be caught, not thrown: this is         -- the race the start/status path hit before the socket was bound.-        result <- runIO' $ isDaemonReady "/tmp/tricorder-isdaemonready-absent.sock"+        result <- runIO' $ isDaemonReady (Path.absolute @"/tmp/tricorder-isdaemonready-absent.sock")         result @?= False     , testCase "returns True once a socket is bound and listening" do-        let path = "/tmp/tricorder-isdaemonready-bound.sock"+        let path = Path.absolute @"/tmp/tricorder-isdaemonready-bound.sock"         result <- runIO' do-            void $ trySync $ FileSystem.removeFile path+            void $ trySync $ File.remove path             _ <- UnixSocket.bind path             isDaemonReady path-        runIO' $ void $ trySync $ FileSystem.removeFile path+        runIO' $ void $ trySync $ File.remove path         result @?= True     ] @@ -75,10 +76,10 @@ --------------------------------------------------------------------------------  -- | Run scripted socket operations (no Delay needed).-runScripted :: [SocketScript] -> Eff '[UnixSocket, File, IOE] a -> IO a-runScripted script = runEff . File.run . UnixSocket.runScripted script+runScripted :: [SocketScript] -> Eff '[UnixSocket, Handles, IOE] a -> IO a+runScripted script = runEff . Handles.run . UnixSocket.runScripted script   -- | Run socket operations against the real IO interpreter.-runIO' :: Eff '[UnixSocket, File, FileSystem, IOE] a -> IO a-runIO' = runEff . FileSystem.runIO . File.run . UnixSocket.runIO+runIO' :: Eff '[UnixSocket, Handles, FileSystem, IOE] a -> IO a+runIO' = runEff . runFileSystem . Handles.run . UnixSocket.runIO
test/Unit/Tricorder/SourceLookupSpec.hs view
@@ -1,17 +1,16 @@ module Unit.Tricorder.SourceLookupSpec (test_SourceLookup) where  import Atelier.Effects.Env (Env)-import Atelier.Effects.FileSystem (FileSystem (..)) import Atelier.Effects.Input (Input) import Atelier.Effects.Log (Log)+import Atelier.FileSystem.Path ((</>)) import Data.Default (def) import Distribution.PackageDescription.Parsec (parseGenericPackageDescriptionMaybe)-import Effectful (IOE, runEff)+import Effectful (IOE) import Effectful.Concurrent (Concurrent, runConcurrent) import Effectful.Dispatch.Dynamic (interpret_)-import Effectful.State.Static.Shared (State, evalState, gets, modify)-import System.FilePath ((</>))-import Test.Tasty (TestTree, testGroup)+import Effectful.FileSystem (FileSystem)+import Test.Tasty (DependencyType (AllFinish), TestTree, dependentTestGroup, testGroup) import Test.Tasty.HUnit (testCase, (@?=)) import Tricorder.SourceLookup.ModuleSourceResult (ModuleSourceResult (..)) import Tricorder.SourceLookup.ReexportLimits (ReexportLimits (..), defaultReexportLimits)@@ -20,11 +19,11 @@ import Atelier.Effects.Env qualified as Env import Atelier.Effects.Input qualified as Input import Atelier.Effects.Log qualified as Log+import Atelier.FileSystem.Path qualified as Path import Codec.Archive.Tar qualified as Tar import Codec.Archive.Tar.Entry qualified as Tar import Codec.Compression.GZip qualified as GZip import Data.ByteString.Lazy qualified as BSL-import Data.List qualified as List import Data.Map.Strict qualified as Map import Data.Text qualified as T @@ -37,6 +36,7 @@ import Tricorder.SourceLookup.GhcPkg (GhcPkg, GhcPkgScript (..), runGhcPkgScripted) import Tricorder.SourceLookup.Hackage (Hackage (..), Result (..)) import Tricorder.SourceLookup.PackageStore (PackageStore)+import Unit.Tricorder.Session.Helpers (withHome, withProjectFiles)  import Tricorder.Session.Stage.Build.Session qualified as Build import Tricorder.SourceLookup.PackageStore qualified as PackageStore@@ -44,8 +44,11 @@  test_SourceLookup :: TestTree test_SourceLookup =-    testGroup+    -- The package store resolves its cache dir from $HOME, which is+    -- process-global, so these must not run concurrently.+    dependentTestGroup         "SourceLookup"+        AllFinish         [ testGroup             "lookupModuleSource"             [ testCase "reads the whole module from a cached tarball" do@@ -158,29 +161,30 @@         , testGroup             "project modules"             [ testCase "resolves every component's source dirs against the package dir" do-                projectDirs @?= ProjectSourceDirs ["/p/src", "/p/test"]+                projectSourceDirs [projectCabalFile (Path.absolute @"/")]+                    @?= ProjectSourceDirs [Path.absolute @"/p/src", Path.absolute @"/p/test"]             , testCase "reads a module from the project's source dirs" do                 result <--                    runTest [] projectFiles noFetch-                        $ lookupModuleSource projectDirs defaultReexportLimits (wholeModule "Proj.Types")+                    runTestAt [] projectFiles noFetch+                        $ \root -> lookupModuleSource (projectDirs root) defaultReexportLimits (wholeModule "Proj.Types")                 result @?= SourceFound (wholeModule "Proj.Types") projectTypesSource             , testCase "reads a module from a non-library component's source dirs" do                 result <--                    runTest [] projectFiles noFetch-                        $ lookupModuleSource projectDirs defaultReexportLimits (wholeModule "Proj.Helpers")+                    runTestAt [] projectFiles noFetch+                        $ \root -> lookupModuleSource (projectDirs root) defaultReexportLimits (wholeModule "Proj.Helpers")                 result @?= SourceFound (wholeModule "Proj.Helpers") projectHelpersSource             , testCase "slices a symbol from a project module" do                 result <--                    runTest [] projectFiles noFetch-                        $ lookupModuleSource projectDirs defaultReexportLimits (symbol "Proj.Types" "greeting")+                    runTestAt [] projectFiles noFetch+                        $ \root -> lookupModuleSource (projectDirs root) defaultReexportLimits (symbol "Proj.Types" "greeting")                 result                     @?= SourceFound                         (symbol "Proj.Types" "greeting")                         "-- | A greeting.\ngreeting :: Text\ngreeting = \"hi\""             , testCase "follows a re-export to another project module" do                 result <--                    runTest [] projectFiles noFetch-                        $ lookupModuleSource projectDirs defaultReexportLimits (symbol "Proj" "greeting")+                    runTestAt [] projectFiles noFetch+                        $ \root -> lookupModuleSource (projectDirs root) defaultReexportLimits (symbol "Proj" "greeting")                 result                     @?= SourceReexported                         (symbol "Proj" "greeting")@@ -188,11 +192,11 @@                         "-- | A greeting.\ngreeting :: Text\ngreeting = \"hi\""             , testCase "follows a re-export from a project module into a package" do                 result <--                    runTest+                    runTestAt                         [NextFindModule (Just "aeson-2.2.5.0")]                         (projectFiles <> withTarball)                         noFetch-                        $ lookupModuleSource projectDirs defaultReexportLimits (symbol "Proj" "encode")+                        $ \root -> lookupModuleSource (projectDirs root) defaultReexportLimits (symbol "Proj" "encode")                 result                     @?= SourceReexported                         (symbol "Proj" "encode")@@ -200,11 +204,11 @@                         "-- | Encode a value as JSON.\nencode :: Value -> ByteString\nencode = undefined"             , testCase "falls back to installed packages for a module not in the project" do                 result <--                    runTest+                    runTestAt                         [NextFindModule (Just "aeson-2.2.5.0")]                         (projectFiles <> withTarball)                         noFetch-                        $ lookupModuleSource projectDirs defaultReexportLimits (wholeModule "Data.Aeson")+                        $ \root -> lookupModuleSource (projectDirs root) defaultReexportLimits (wholeModule "Data.Aeson")                 result @?= SourceFound (wholeModule "Data.Aeson") moduleSource             ]         ]@@ -227,9 +231,10 @@   -- | The cabal cache path the fixture package resolves to under @HOME=\/h@.-tarballPath :: FilePath+tarballPath :: Path.Relative tarballPath =-    "/h/.cache/cabal/packages" </> "hackage.haskell.org/aeson/2.2.5.0/aeson-2.2.5.0.tar.gz"+    Path.rel @"h/.cache/cabal/packages"+        </> Path.rel @"hackage.haskell.org/aeson/2.2.5.0/aeson-2.2.5.0.tar.gz"   -- | A gzipped tar holding the fixture module under a @src\/@ layout.@@ -238,25 +243,25 @@   -- | A filesystem in which the fixture tarball is already cached.-withTarball :: Map FilePath LByteString+withTarball :: Map Path.Relative LByteString withTarball = Map.singleton tarballPath tarballBytes   -- | The legacy (pre-XDG) cabal cache path under @HOME=\/h@.-legacyTarballPath :: FilePath+legacyTarballPath :: Path.Relative legacyTarballPath =-    "/h/.cabal/packages" </> "hackage.haskell.org/aeson/2.2.5.0/aeson-2.2.5.0.tar.gz"+    Path.rel @"h/.cabal/packages" </> Path.rel @"hackage.haskell.org/aeson/2.2.5.0/aeson-2.2.5.0.tar.gz"   -- | A filesystem in which the fixture tarball lives only in the legacy cache.-withLegacyTarball :: Map FilePath LByteString+withLegacyTarball :: Map Path.Relative LByteString withLegacyTarball = Map.singleton legacyTarballPath tarballBytes   -- | A project package with a library under @src@ and a test suite under @test@.-projectCabalFile :: CabalFile-projectCabalFile =-    CabalFile "/p/proj.cabal"+projectCabalFile :: Path.Absolute -> CabalFile+projectCabalFile root =+    CabalFile (root </> Path.rel @"p/proj.cabal")         . fromMaybe (error "projectCabalFile: unparseable")         . parseGenericPackageDescriptionMaybe         . encodeUtf8@@ -275,8 +280,8 @@             ]  -projectDirs :: ProjectSourceDirs-projectDirs = projectSourceDirs [projectCabalFile]+projectDirs :: Path.Absolute -> ProjectSourceDirs+projectDirs root = projectSourceDirs [projectCabalFile root]   noProjectDirs :: ProjectSourceDirs@@ -300,25 +305,25 @@  -- | The source files of 'projectCabalFile': @Proj@ re-exports @greeting@ from -- @Proj.Types@ and @encode@ from the installed @Data.Aeson@.-projectFiles :: Map FilePath LByteString+projectFiles :: Map Path.Relative LByteString projectFiles =     Map.fromList         [-            ( "/p/src/Proj.hs"+            ( Path.rel @"p/src/Proj.hs"             , encodeUtf8 @Text                 "module Proj (greeting, encode) where\n\nimport Proj.Types (greeting)\nimport Data.Aeson (encode)\n"             )-        , ("/p/src/Proj/Types.hs", encodeUtf8 projectTypesSource)-        , ("/p/test/Proj/Helpers.hs", encodeUtf8 projectHelpersSource)+        , (Path.rel @"p/src/Proj/Types.hs", encodeUtf8 projectTypesSource)+        , (Path.rel @"p/test/Proj/Helpers.hs", encodeUtf8 projectHelpersSource)         ]   -- | A package in which @A@ re-exports @foo@ from @B@, which re-exports it from -- @C@, which defines it.-withChainTarball :: Map FilePath LByteString+withChainTarball :: Map Path.Relative LByteString withChainTarball =     Map.singleton-        ("/h/.cache/cabal/packages" </> "hackage.haskell.org/chain/1.0/chain-1.0.tar.gz")+        (Path.rel @"h/.cache/cabal/packages" </> Path.rel @"hackage.haskell.org/chain/1.0/chain-1.0.tar.gz")         $ mkTarballWith             [ ("chain-1.0/src/A.hs", T.unlines ["module A (foo) where", "", "import B (foo)"])             , ("chain-1.0/src/B.hs", T.unlines ["module B (foo) where", "", "import C"])@@ -338,10 +343,10 @@  -- | A package whose @Data.Reex@ re-exports @pack@ (and claims to re-export -- @unpack@) from @Data.Reex.Internal@, which only defines @pack@.-withReexportTarball :: Map FilePath LByteString+withReexportTarball :: Map Path.Relative LByteString withReexportTarball =     Map.singleton-        ("/h/.cache/cabal/packages" </> "hackage.haskell.org/reex/1.0/reex-1.0.tar.gz")+        (Path.rel @"h/.cache/cabal/packages" </> Path.rel @"hackage.haskell.org/reex/1.0/reex-1.0.tar.gz")         $ mkTarballWith             [                 ( "reex-1.0/src/Data/Reex.hs"@@ -400,11 +405,10 @@ type FetchEffects =     '[ PackageStore      , Env-     , FileSystem-     , State (Map FilePath LByteString)      , Input Build.Session      , Log      , Concurrent+     , FileSystem      , IOE      ] @@ -414,51 +418,43 @@  runTest     :: [GhcPkgScript]-    -> Map FilePath LByteString+    -> Map Path.Relative LByteString     -> Eff FetchEffects Result     -> Eff TestEffects a     -> IO a runTest pkgScript initialFs onFetch action =-    runEff-        . runConcurrent-        . Log.runNoOp-        . Input.withConst (def :: Build.Session)-        . evalState initialFs-        . runFileSystemFake-        . Env.runConst [("HOME", "/h")]-        . PackageStore.run-        . runHackageWith onFetch-        . runGhcPkgScripted pkgScript-        $ action+    runTestAt pkgScript initialFs onFetch (const action)  +-- | Run against a real temporary directory seeded with @initialFs@ (paths+-- relative to it), which doubles as the test's @$HOME@ (at @h/@) and, for+-- project modules, the parent of the project package (at @p/@). The action+-- receives the directory's path.+--+-- 'Effectful.FileSystem' only has a real-IO interpreter, so the package cache+-- and project sources have to exist on disk. @$HOME@ is process-global; see+-- 'test_SourceLookup'.+runTestAt+    :: [GhcPkgScript]+    -> Map Path.Relative LByteString+    -> Eff FetchEffects Result+    -> (Path.Absolute -> Eff TestEffects a)+    -> IO a+runTestAt pkgScript initialFs onFetch action =+    withProjectFiles (BSL.toStrict <$> initialFs) \root ->+        withHome (root </> Path.rel @"h")+            . runConcurrent+            . Log.runNoOp+            . Input.withConst (def :: Build.Session)+            . Env.runConst []+            . PackageStore.run+            . runHackageWith onFetch+            . runGhcPkgScripted pkgScript+            $ action root++ -- | A scripted 'Hackage' interpreter: every 'fetchPackage' yields the given -- action's result. runHackageWith :: Eff es Result -> Eff (Hackage : es) a -> Eff es a runHackageWith onFetch = interpret_ \case     FetchPackage _ -> onFetch----- | A 'FileSystem' backed by an in-memory map, with directory semantics good--- enough for the cabal-cache layout: 'doesPathExist' treats a key as living--- under any of its path prefixes (or being one), 'doesDirectoryExist' requires--- something strictly under it, and 'listDirectory' returns immediate child--- names (so a repo subdir like @hackage.haskell.org@ is discoverable).-runFileSystemFake-    :: (State (Map FilePath LByteString) :> es)-    => Eff (FileSystem : es) a -> Eff es a-runFileSystemFake = interpret_ \case-    DoesFileExist p -> gets (Map.member p)-    DoesPathExist p -> gets (any (isUnder p) . Map.keys)-    DoesDirectoryExist p -> gets (any (isStrictlyUnder p) . Map.keys)-    ListDirectory p -> gets (ordNub . mapMaybe (childName p) . Map.keys)-    ReadFileLbsFrom p _ -> gets (fromMaybe "" . Map.lookup p)-    CreateDirectoryIfMissing _ _ -> pure ()-    WriteFileBS p bytes -> modify (Map.insert p (BSL.fromStrict bytes))-    _ -> error "runFileSystemFake: unexpected operation"-  where-    isUnder p k = p == k || isStrictlyUnder p k-    isStrictlyUnder p k = (p <> "/") `List.isPrefixOf` k-    childName p k = case List.stripPrefix (p <> "/") k of-        Just rest | not (null rest) -> Just (takeWhile (/= '/') rest)-        _ -> Nothing
tricorder.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:            tricorder-version:         1.0.0.0+version:         1.1.0.0 synopsis:        Continuous Haskell build status, diagnostics, and tests via a shared daemon description:     tricorder rebuilds your Haskell project continuously and surfaces build status, diagnostics, test results, and documentation - for developers and LLM coding agents. Like ghcid and ghciwatch it reloads on every change, but builds run in a background daemon so multiple clients (an interactive TUI, a status CLI, an agent skill) share a single build state without triggering redundant rebuilds. It discovers components across multi-package cabal.project workspaces automatically and ships context-friendly output for agentic use via the CLI. category:        Development@@ -32,11 +32,19 @@  library tricorder-internal   exposed-modules:-      Tricorder.Build       Tricorder.Build.ByteSize       Tricorder.Build.Changes+      Tricorder.Build.Diagnostic+      Tricorder.Build.DiagnosticLocation       Tricorder.Build.Duration       Tricorder.Build.EvalComment+      Tricorder.Build.Id+      Tricorder.Build.Phase+      Tricorder.Build.PostBuild+      Tricorder.Build.Progress+      Tricorder.Build.Result+      Tricorder.Build.Severity+      Tricorder.Build.State       Tricorder.Build.Test       Tricorder.CLI.App       Tricorder.CLI.App.CLIResponse@@ -44,11 +52,11 @@       Tricorder.CLI.App.Output       Tricorder.CLI.App.Test       Tricorder.CLI.App.Test.Json-      Tricorder.CLI.App.Test.Json.Responses       Tricorder.CLI.App.Test.SuiteView       Tricorder.CLI.App.Test.Text       Tricorder.CLI.Arguments       Tricorder.CLI.Daemon+      Tricorder.CLI.Docs       Tricorder.CLI.Main       Tricorder.CLI.Operations       Tricorder.CLI.Render@@ -97,7 +105,13 @@       Tricorder.Daemon.TestRunner       Tricorder.Daemon.Watch       Tricorder.Logging-      Tricorder.Runtime+      Tricorder.Runtime.Cache+      Tricorder.Runtime.Directory+      Tricorder.Runtime.LogPath+      Tricorder.Runtime.PidFile+      Tricorder.Runtime.ProjectHash+      Tricorder.Runtime.ProjectRoot+      Tricorder.Runtime.SocketPath       Tricorder.Session       Tricorder.Session.CabalFile       Tricorder.Session.Command.RenderedCommand@@ -171,8 +185,9 @@     , Cabal-syntax >=3.12 && <3.17     , Glob ==0.10.*     , aeson >=2.2 && <2.4-    , atelier-core ==1.0.*+    , atelier-core ==1.1.*     , atelier-prelude ==0.4.*+    , autodocodec >=0.6 && <0.8     , base >=4.18 && <4.23     , brick ==3.0.*     , bytestring >=0.11 && <0.13@@ -200,8 +215,8 @@     , text ==2.1.*     , time >=1.12 && <1.17     , time-units ==1.0.*-    , tricorder-types ==1.0.*-    , vty >=6.5 && <6.7+    , tricorder-types ==1.1.*+    , vty >=6.5 && <6.8     , vty-crossplatform ==0.5.*     , yaml ==0.11.*     , zlib ==0.7.*@@ -211,6 +226,44 @@   if impl(GHC >= 9.8)     ghc-options: -Wno-missing-poly-kind-signatures -Wno-missing-role-annotations +executable help+  main-is: Main.hs+  other-modules:+      Paths_tricorder+  autogen-modules:+      Paths_tricorder+  hs-source-dirs:+      help+  default-extensions:+      BlockArguments+      DataKinds+      DeriveAnyClass+      DerivingStrategies+      DerivingVia+      DuplicateRecordFields+      FlexibleContexts+      GADTs+      LambdaCase+      MultiWayIf+      OverloadedLabels+      OverloadedRecordDot+      OverloadedStrings+      StrictData+      TemplateHaskell+      TypeFamilies+  ghc-options: -Weverything -Wno-unsafe -Wno-missing-safe-haskell-mode -Wno-monomorphism-restriction -Wno-missing-kind-signatures -Wno-missing-local-signatures -Wno-missing-import-lists -Wno-implicit-prelude -Wno-unticked-promoted-constructors -Wno-unused-packages -Wno-all-missed-specialisations -Wno-missed-specialisations -fplugin=Effectful.Plugin -threaded "-with-rtsopts=-N -T"+  build-depends:+      atelier-prelude ==0.4.*+    , base >=4.18 && <4.23+    , effectful-core ==2.7.*+    , effectful-plugin ==2.2.*+    , tricorder-internal+  mixins:+      base hiding (Prelude)+  default-language: GHC2021+  if impl(GHC >= 9.8)+    ghc-options: -Wno-missing-poly-kind-signatures -Wno-missing-role-annotations+ executable tricorder   main-is: Main.hs   other-modules:@@ -293,10 +346,10 @@   other-modules:       Unit.Tricorder.Build.ByteSizeSpec       Unit.Tricorder.Build.EvalCommentSpec+      Unit.Tricorder.Build.StateSpec       Unit.Tricorder.CLI.App.Test.SuiteViewSpec       Unit.Tricorder.CLI.RenderSpec       Unit.Tricorder.Daemon.BuilderSpec-      Unit.Tricorder.Daemon.BuildStateSpec       Unit.Tricorder.Daemon.DispatchSpec       Unit.Tricorder.Daemon.Ghci.LoadResultSpec       Unit.Tricorder.Daemon.Ghci.OutputSpec@@ -305,10 +358,12 @@       Unit.Tricorder.Daemon.Ghci.SessionSpec       Unit.Tricorder.Daemon.TestRunnerSpec       Unit.Tricorder.Daemon.WatchSpec+      Unit.Tricorder.Runtime.ProjectRootSpec       Unit.Tricorder.Session.CabalFileSpec       Unit.Tricorder.Session.CommandTemplateSpec       Unit.Tricorder.Session.Helpers       Unit.Tricorder.Session.ReplSpec+      Unit.Tricorder.Session.StackProjectSpec       Unit.Tricorder.Session.Stage.Build.CommandSpec       Unit.Tricorder.Session.Stage.Eval.CommandSpec       Unit.Tricorder.Session.Stage.Eval.SessionSpec@@ -353,7 +408,7 @@   build-depends:       Cabal-syntax >=3.12 && <3.17     , aeson >=2.2 && <2.4-    , atelier-core ==1.0.*+    , atelier-core ==1.1.*     , atelier-prelude ==0.4.*     , base >=4.18 && <4.23     , bytestring >=0.11 && <0.13@@ -375,10 +430,11 @@     , time >=1.12 && <1.17     , time-units ==1.0.*     , tricorder-internal-    , tricorder-types ==1.0.*+    , tricorder-types ==1.1.*     , typed-process ==0.2.*     , unagi-chan ==0.4.*     , unix ==2.8.*+    , yaml ==0.11.*     , zlib ==0.7.*   mixins:       base hiding (Prelude)