packages feed

canontra-0.4.0.0: src/Canontra/Repository/Repository.hs

{-# LANGUAGE BangPatterns #-}
{- |
Module      : Canontra.Repository.Repository
Description : Deterministic polyglot repository traversal and aggregated Merkle fingerprinting.

A repository is more than the sum of its files: it is an ordered collection.
By sorting file paths and aggregating individual structural fingerprints into
a canonical tree hash (F_R), canontra guarantees that filesystem traversal order
never affects the resulting repository identity across Python, JS, TS, Go, and Rust.
Includes cross-platform POSIX path normalization and incremental CNTR\x07 slab caching.
-}
module Canontra.Repository.Repository
  ( fingerprintDirectory
  , fingerprintDirectoryWithCache
  , computeRepositoryFingerprint
  , computeWholeRepoBundle
  , discoverSourceFiles
  , discoverSourceFilesSafe
  , discoverPythonFiles
  , formatRepositoryManifest
  , normalizePathPosix
  , normalizePathCanonical
  ) where

import Control.Applicative ((<|>))
import Control.Exception (IOException, try)
import Control.Monad (forM)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder as BB
import Data.Char (toLower)
import Data.Either (partitionEithers)
import Data.List (sort)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import System.Directory (canonicalizePath, createDirectoryIfMissing, doesDirectoryExist, doesFileExist, listDirectory)
import System.FilePath ((</>), makeRelative, takeDirectory, takeExtension)
import System.IO (hPutStrLn, stderr)

import Canontra.Analysis.WholeRepoGraph
  ( FileGraphSummary
  , buildWholeRepoCallGraphFromSummaries
  , buildWholeRepoDataFlowFromSummaries
  , extractFileGraphSummary
  , toCSRCallGraph
  , toCSRDataFlowGraph
  )
import Canontra.Cache.Common (MerkleCache (..), MerkleCacheEntry (..))
import Canontra.Cache.Inode (FileMetadata (..), getFileMetadata)
import Canontra.Cache.MerkleCache (defaultCachePath, readMerkleCache)
import Canontra.Cache.SlabV6 (saveRepoGraphsSlab)
import Canontra.Cache.SlabV7 (SlabV7Entry (..), readAnySlabCacheForV7, writeSlabV7File)
import Canontra.Canonical.Serialize (canonicalizeWholeRepoCallGraph, canonicalizeWholeRepoDataFlow)
import Canontra.Canonical.StreamingHash (hashBuilderDirect)
import Canontra.Fingerprint.Bundle (computeBundleAndProgram, computeWholeRepoBundleFromHashes)
import Canontra.Fingerprint.Source (hashBytes)
import Canontra.Fingerprint.WholeRepoCallGraph (computeFWCG)
import Canontra.Fingerprint.WholeRepoDataFlow (computeFWDF)
import Canontra.IR.Program (Program)
import Canontra.Normalize.Rules (engineName, engineVersion)
import Canontra.Repository.Parallel (parFingerprintWithPrograms, parMapChunks)
import Canontra.Security.Path (canonicalizeSafePath, checkResourceBounds, isSymlinkLoop, maxRecursionDepth)
import Canontra.Types

repoGraphsCachePath :: FilePath -> FilePath
repoGraphsCachePath rootDir = rootDir </> ".canontra" </> "repo_graphs.txt"

saveRepoGraphs :: FilePath -> Fingerprint -> Fingerprint -> IO ()
saveRepoGraphs rootDir fwcg fwdf = do
  saveRepoGraphsSlab rootDir fwcg fwdf Nothing Nothing
  let p = repoGraphsCachePath rootDir
  createDirectoryIfMissing True (takeDirectory p)
  writeFile p (T.unpack (unFingerprint fwcg) ++ "\n" ++ T.unpack (unFingerprint fwdf))

-- | Universal cross-platform canonical path normalization (POSIX forward slashes + case folding).
normalizePathCanonical :: FilePath -> FilePath
normalizePathCanonical = map (\c -> if c == '\\' then '/' else toLower c)

-- | Normalize Windows backslashes to standard POSIX forward slashes.
normalizePathPosix :: FilePath -> FilePath
normalizePathPosix = map (\c -> if c == '\\' then '/' else c)

fingerprintDirectory :: FilePath -> IO (Either ParseError RepositoryManifest)
fingerprintDirectory rootDir = fingerprintDirectoryWithCache rootDir False

fingerprintDirectoryWithCache :: FilePath -> Bool -> IO (Either ParseError RepositoryManifest)
fingerprintDirectoryWithCache rootDir useCache = do
  srcFiles <- discoverSourceFiles rootDir
  let sortedRelPaths = sort (map (makeRelative rootDir) srcFiles)
  let cachePath = defaultCachePath rootDir
  if not useCache
    then do
      results <- parFingerprintWithPrograms rootDir sortedRelPaths
      let (failures, successes) = partitionEithers results
          fileEntries = map fst successes
          progs = [(normalizePathCanonical (fePath fe), p) | (fe, p) <- successes]
      mapM_ logFailure failures
      if null fileEntries && not (null sortedRelPaths)
        then case failures of
          (e:_) -> pure (Left e)
          []    -> pure (Left (ParseError rootDir 0 0 "No files could be parsed"))
        else do
          let repoFp = computeRepositoryFingerprint fileEntries
              fwcg = computeFWCG progs
              fwdf = computeFWDF progs
          saveRepoGraphs rootDir fwcg fwdf
          let manifest = RepositoryManifest
                { rmEngine = engineName
                , rmVersion = engineVersion
                , rmRepositoryFingerprint = repoFp
                , rmWholeRepoCallGraph = Just fwcg
                , rmWholeRepoDataFlow = Just fwdf
                , rmFiles = fileEntries
                }
          pure (Right manifest)
    else do
      (cachedMap, mCachedRepo) <- loadCacheForV7 cachePath
      results <- parMapChunks (processFileV7Concurrent rootDir cachedMap) sortedRelPaths
      let (failures, successes) = partitionEithers results
          fileEntries = [fe | (fe, _, _, _) <- successes]
          v7Entries   = [v7 | (_, v7, _, _) <- successes]
          summaries   = [sm | (_, _, sm, _) <- successes]
          anyDirty    = any (\(_, _, _, dirty) -> dirty) successes
      mapM_ logFailure failures
      if null fileEntries && not (null sortedRelPaths)
        then case failures of
          (e:_) -> pure (Left e)
          []    -> pure (Left (ParseError rootDir 0 0 "No files could be parsed"))
        else do
          let !repoFp = computeRepositoryFingerprint fileEntries
              !currentKeySet = Set.fromList [normalizePathCanonical (fePath fe) | fe <- fileEntries]
              !sameFileSet = currentKeySet == Map.keysSet cachedMap
          (!fwcg, !fwdf) <- case (not anyDirty && sameFileSet, mCachedRepo) of
            (True, Just (wrb, _, _))
              | not (T.null (unFingerprint (wrbCallGraph wrb)))
                  && not (T.null (unFingerprint (wrbDataFlow wrb))) ->
                  pure (wrbCallGraph wrb, wrbDataFlow wrb)
            _ -> do
              let !wcg = buildWholeRepoCallGraphFromSummaries summaries
                  !wdf = buildWholeRepoDataFlowFromSummaries summaries
                  !c   = hashBytes (canonicalizeWholeRepoCallGraph wcg)
                  !d   = hashBytes (canonicalizeWholeRepoDataFlow wdf)
                  (!cgCSR, _) = toCSRCallGraph wcg
                  (!dfCSR, _) = toCSRDataFlowGraph wdf
                  !wrb = computeWholeRepoBundleFromHashes repoFp c d
              writeSlabV7File cachePath v7Entries (Just (wrb, cgCSR, dfCSR))
              pure (c, d)
          let manifest = RepositoryManifest
                { rmEngine = engineName
                , rmVersion = engineVersion
                , rmRepositoryFingerprint = repoFp
                , rmWholeRepoCallGraph = Just fwcg
                , rmWholeRepoDataFlow = Just fwdf
                , rmFiles = fileEntries
                }
          pure (Right manifest)
  where
    logFailure err =
      hPutStrLn stderr $ "[Canontra Parse Warning] " ++ peFile err ++ ":" ++ show (peLine err) ++ ":" ++ show (peColumn err) ++ ": " ++ T.unpack (peReason err)

    loadCacheForV7 cPath = do
      exists <- doesFileExist cPath
      if not exists
        then pure (Map.empty, Nothing)
        else do
          bs <- BS.readFile cPath
          case readAnySlabCacheForV7 bs of
            Just res -> pure res
            Nothing -> do
              MerkleCache legacyMap <- readMerkleCache cPath
              let upgraded = Map.mapWithKey
                    (\p (MerkleCacheEntry sz mt b) -> SlabV7Entry (FileMetadata p sz mt) b Nothing)
                    legacyMap
              pure (upgraded, Nothing)

    processFileV7Concurrent :: FilePath -> Map.Map FilePath SlabV7Entry -> FilePath -> IO (Either ParseError (FileEntry, SlabV7Entry, FileGraphSummary, Bool))
    processFileV7Concurrent rDir cachedMap relPath = do
      let fullPath = rDir </> relPath
          normPath = normalizePathCanonical relPath
      mMeta <- getFileMetadata fullPath
      case mMeta of
        Just meta
          | Just entry <- Map.lookup normPath cachedMap <|> Map.lookup relPath cachedMap
          , fmSize (sv7Meta entry) == fmSize meta
          , fmMtime (sv7Meta entry) == fmMtime meta
          , Just summary <- sv7Summary entry ->
              let !metaNorm = meta { fmPath = normPath }
                  !entryNorm = entry { sv7Meta = metaNorm }
              in pure (Right (FileEntry relPath (sv7Bundle entry), entryNorm, summary, False))
        _ -> do
          rawBytes <- BS.readFile fullPath
          let textContent = TE.decodeUtf8Lenient rawBytes
          case computeBundleAndProgram relPath rawBytes textContent of
            Left err -> pure (Left err)
            Right (b, prog) ->
              let !summary = extractFileGraphSummary normPath prog
                  !meta = case mMeta of
                            Just m  -> m { fmPath = normPath }
                            Nothing -> FileMetadata normPath 0 0
                  !v7Entry = SlabV7Entry meta b (Just summary)
              in pure (Right (FileEntry relPath b, v7Entry, summary, True))

computeRepositoryFingerprint :: [FileEntry] -> Fingerprint
computeRepositoryFingerprint entries =
  let pairs = [(normalizePathCanonical (fePath e), unFingerprint (f4Composite (feFingerprints e))) | e <- entries]
      sortedPairs = sort pairs
      builder = foldMap (\(p, f) -> BB.string8 p <> BB.char8 ':' <> BB.byteString (TE.encodeUtf8 f) <> BB.char8 ';') sortedPairs
  in hashBuilderDirect builder

-- | Compute whole-repository bundle combining F_R, F_WCG, F_WDF, and F_W4.
computeWholeRepoBundle :: [(FilePath, Program)] -> [FileEntry] -> WholeRepoBundle
computeWholeRepoBundle progs entries =
  let fr = computeRepositoryFingerprint entries
      fwcg = computeFWCG progs
      fwdf = computeFWDF progs
      combined = TE.encodeUtf8 (unFingerprint fr <> unFingerprint fwcg <> unFingerprint fwdf)
      fw4 = hashBytes combined
  in WholeRepoBundle fr fwcg fwdf fw4


discoverSourceFilesSafe :: FilePath -> IO (Either String [FilePath])
discoverSourceFilesSafe rootDir
  | any (== '\0') rootDir = pure (Left "Security violation: repository path contains null byte")
  | otherwise = do
      isDir <- doesDirectoryExist rootDir
      if not isDir
        then do
          isFile <- doesFileExist rootDir
          if isFile && isSupportedExt (takeExtension rootDir)
            then do
              bCheck <- checkResourceBounds rootDir
              case bCheck of
                Left err -> pure (Left err)
                Right () -> pure (Right [rootDir])
            else pure (Right [])
        else do
          eCanonRoot <- try (canonicalizePath rootDir) :: IO (Either IOException FilePath)
          case eCanonRoot of
            Left err -> pure (Left ("Failed to canonicalize repository root: " ++ show err))
            Right canonRoot -> do
              (_, initVisited) <- isSymlinkLoop Set.empty canonRoot
              files <- traverseDir canonRoot initVisited 0 rootDir
              pure (Right files)
  where
    traverseDir canonRoot visited depth currentDir
      | depth >= maxRecursionDepth = pure []
      | otherwise = do
          contentsRes <- try (listDirectory currentDir) :: IO (Either IOException [FilePath])
          case contentsRes of
            Left _ -> pure []
            Right contents -> do
              let filtered = filter (`notElem` ignoredDirs) contents
              fpaths <- forM filtered $ \item -> do
                let full = currentDir </> item
                isSubDir <- doesDirectoryExist full
                if isSubDir
                  then do
                    contained <- canonicalizeSafePath canonRoot full
                    case contained of
                      Left _ -> pure [] -- Symlink pointing outside repository root
                      Right _ -> do
                        (isLoop, newVisited) <- isSymlinkLoop visited full
                        if isLoop
                          then pure [] -- Symlink cycle detected and broken safely!
                          else traverseDir canonRoot newVisited (depth + 1) full
                  else if isSupportedExt (takeExtension item)
                    then do
                      contained <- canonicalizeSafePath canonRoot full
                      case contained of
                        Left _ -> pure [] -- Symlink file pointing outside repository root
                        Right _ -> do
                          bounds <- checkResourceBounds full
                          case bounds of
                            Left _ -> pure [] -- File size exceeds 50MB ceiling
                            Right () -> pure [full]
                    else pure []
              pure (concat fpaths)

discoverSourceFiles :: FilePath -> IO [FilePath]
discoverSourceFiles dir = do
  res <- discoverSourceFilesSafe dir
  case res of
    Left _ -> pure []
    Right files -> pure files

discoverPythonFiles :: FilePath -> IO [FilePath]
discoverPythonFiles = discoverSourceFiles

isSupportedExt :: String -> Bool
isSupportedExt ext = ext `elem`
  [ ".py", ".pyi"
  , ".js", ".jsx", ".mjs", ".cjs"
  , ".ts", ".tsx"
  , ".go"
  , ".rs"
  ]

ignoredDirs :: [FilePath]
ignoredDirs =
  [ ".git", ".hg", ".svn", "__pycache__", ".venv", "venv", ".mypy_cache"
  , ".pytest_cache", ".tox", ".stack-work", "node_modules", "target", "vendor", "dist", "build", ".canontra"
  ]

formatRepositoryManifest :: RepositoryManifest -> T.Text
formatRepositoryManifest rm =
  T.unlines $
    [ "================================================================================"
    , "  CANONTRA DETERMINISTIC REPOSITORY MANIFEST"
    , "================================================================================"
    , "  Repository Hash (F_R): " <> unFingerprint (rmRepositoryFingerprint rm)
    , "  Indexed File Count:    " <> T.pack (show (length (rmFiles rm))) <> " source files"
    , "  Engine:                " <> rmEngine rm <> " " <> rmVersion rm
    , "--------------------------------------------------------------------------------"
    , "  Indexed Source File                               Structural Fingerprint (F1)"
    , "--------------------------------------------------------------------------------"
    ]
    ++ map (\fe -> "  " <> T.justifyLeft 50 ' ' (T.pack (fePath fe)) <> unFingerprint (f1Structural (feFingerprints fe))) (rmFiles rm)
    ++ [ "================================================================================" ]