packages feed

canontra-0.4.0.0: src/Canontra/Harness/Store.hs

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StrictData #-}

{- |
Module      : Canontra.Harness.Store
Description : Content-addressed snapshot store (.canontra/snaps/) for AI harness sub-versioning.

Provides a zero-daemon, zero-.git-mutation local store under @.canontra/snaps/@:
  - @HEAD@ pointer to the active @snap_id@
  - @ledger.jsonl@ append-only turn metadata ledger
  - @objects/<ab>/<cdef...>@ SHA-256 content-addressed @F0@ source blobs
  - @manifests/<snap_id>.json@ complete snapshot manifests

All writes use temp files + atomic swap ('atomicSwapWithRetry_'), and all reads
for workspace restoration verify SHA-256 integrity and path containment before
any mutation occurs.
-}
module Canontra.Harness.Store
  ( -- * Schema & Classification Types
    SnapClassification (..)
  , classificationText
  , parseClassificationText
  , SnapFileRecord (..)
  , SnapFileDelta (..)
  , SnapManifest (..)
  , LedgerEntry (..)

    -- * Path Layout & Security Validators
  , canontraStateDir
  , snapsRootDir
  , objectsDir
  , manifestsDir
  , headFilePath
  , ledgerFilePath
  , manifestFilePath
  , objectBlobPath
  , isSafeSnapId
  , isValidSha256Hex
  , isSafeRelativeFilePath
  , getCurrentPidString

    -- * Store Lifecycle & Atomic I/O
  , ensureSnapStore
  , readHeadSnapId
  , writeHeadSnapId
  , storeBlobIfAbsent
  , readVerifiedBlob
  , writeSnapManifest
  , resolveSnapId
  , readSnapManifest
  , readSnapManifestDirect
  , appendLedgerEntry
  , readLedgerEntries
  , listAllManifestIds
  , removeManifestFile
  ) where

import Control.DeepSeq (NFData)
import Control.Exception (IOException, try)
import qualified Data.Aeson as Aeson
import Data.Aeson (FromJSON (..), ToJSON (..), object, (.=), (.:), (.:?))
import qualified Data.Aeson.Encode.Pretty as AesonPretty
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Char8 as LBSC
import Data.Char (isAlphaNum, isHexDigit)
import Data.List (isPrefixOf, sort)
import Data.Map.Strict (Map)
import Data.Maybe (mapMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import GHC.Generics (Generic)
import System.Directory
  ( createDirectoryIfMissing
  , doesFileExist
  , listDirectory
  , removeFile
  )
import System.FilePath
  ( dropExtension
  , splitDirectories
  , takeDirectory
  , takeExtension
  , (</>)
  )
import System.Posix.Internals (c_getpid)

import Canontra.Cache.Common (atomicSwapWithRetry_)
import Canontra.Fingerprint.Source (computeF0)
import Canontra.Types (Fingerprint (..), FingerprintBundle)

-- | Semantic classification of a snapshot transition.
data SnapClassification
  = SnapNoChange
  | SnapSemanticNoop
  | SnapInternalLogic
  | SnapContractChange
  deriving stock (Eq, Ord, Show, Generic)
  deriving anyclass (NFData)

-- | Wire string representation of 'SnapClassification'.
classificationText :: SnapClassification -> Text
classificationText = \case
  SnapNoChange       -> "no_change"
  SnapSemanticNoop   -> "semantic_noop"
  SnapInternalLogic  -> "internal_logic"
  SnapContractChange -> "contract_change"

-- | Parse wire string representation into 'SnapClassification'.
parseClassificationText :: Text -> Maybe SnapClassification
parseClassificationText = \case
  "no_change"       -> Just SnapNoChange
  "semantic_noop"   -> Just SnapSemanticNoop
  "internal_logic"  -> Just SnapInternalLogic
  "contract_change" -> Just SnapContractChange
  _                 -> Nothing

instance ToJSON SnapClassification where
  toJSON = toJSON . classificationText

instance FromJSON SnapClassification where
  parseJSON = Aeson.withText "SnapClassification" $ \txt ->
    case parseClassificationText txt of
      Just c  -> pure c
      Nothing -> fail ("Unknown SnapClassification: " ++ T.unpack txt)

-- | Stored metadata + 9-tier fingerprint bundle for a single file in a snapshot.
data SnapFileRecord = SnapFileRecord
  { sfrPath   :: !FilePath
  , sfrF0     :: !Text
  , sfrSize   :: !Integer
  , sfrBundle :: !FingerprintBundle
  } deriving stock (Eq, Show, Generic)
    deriving anyclass (NFData)

instance ToJSON SnapFileRecord where
  toJSON r = object
    [ "path"   .= sfrPath r
    , "f0"     .= sfrF0 r
    , "size"   .= sfrSize r
    , "bundle" .= sfrBundle r
    ]

instance FromJSON SnapFileRecord where
  parseJSON = Aeson.withObject "SnapFileRecord" $ \o ->
    SnapFileRecord
      <$> o .: "path"
      <*> o .: "f0"
      <*> o .: "size"
      <*> o .: "bundle"

-- | Per-file semantic delta entry emitted by @snap mark@ and @snap diff@.
data SnapFileDelta = SnapFileDelta
  { sfdPath           :: !FilePath
  , sfdStatus         :: !Text
  , sfdSeverity       :: !Text
  , sfdMutatedTiers   :: ![Text]
  , sfdInvariantTiers :: ![Text]
  } deriving stock (Eq, Ord, Show, Generic)
    deriving anyclass (NFData)

instance ToJSON SnapFileDelta where
  toJSON d = object
    [ "path"            .= sfdPath d
    , "status"          .= sfdStatus d
    , "severity"        .= sfdSeverity d
    , "mutated_tiers"   .= sfdMutatedTiers d
    , "invariant_tiers" .= sfdInvariantTiers d
    ]

instance FromJSON SnapFileDelta where
  parseJSON = Aeson.withObject "SnapFileDelta" $ \o ->
    SnapFileDelta
      <$> o .: "path"
      <*> o .: "status"
      <*> o .: "severity"
      <*> o .: "mutated_tiers"
      <*> o .: "invariant_tiers"

-- | Complete snapshot manifest stored under @.canontra/snaps/manifests/<snap_id>.json@.
data SnapManifest = SnapManifest
  { smSchemaVersion    :: !Text
  , smStability        :: !Text
  , smSnapId           :: !Text
  , smParentId         :: !(Maybe Text)
  , smTimestamp        :: !Text
  , smLabel            :: !(Maybe Text)
  , smAgent            :: !(Maybe Text)
  , smClassification   :: !SnapClassification
  , smRepoFR           :: !Text
  , smRepoFWCG         :: !(Maybe Text)
  , smRepoFWDF         :: !(Maybe Text)
  , smFiles            :: !(Map FilePath SnapFileRecord)
  , smChangedFiles     :: ![SnapFileDelta]
  , smRecommendedTests :: ![Text]
  , smElapsedMs        :: !Double
  } deriving stock (Eq, Show, Generic)
    deriving anyclass (NFData)

instance ToJSON SnapManifest where
  toJSON m = object
    [ "schema_version"    .= smSchemaVersion m
    , "stability"         .= smStability m
    , "snap_id"           .= smSnapId m
    , "parent_id"         .= smParentId m
    , "timestamp"         .= smTimestamp m
    , "label"             .= smLabel m
    , "agent"             .= smAgent m
    , "classification"    .= smClassification m
    , "repo_f_r"          .= smRepoFR m
    , "repo_f_wcg"        .= smRepoFWCG m
    , "repo_f_wdf"        .= smRepoFWDF m
    , "files"             .= smFiles m
    , "changed_files"     .= smChangedFiles m
    , "recommended_tests" .= smRecommendedTests m
    , "elapsed_ms"        .= smElapsedMs m
    ]

instance FromJSON SnapManifest where
  parseJSON = Aeson.withObject "SnapManifest" $ \o ->
    SnapManifest
      <$> o .: "schema_version"
      <*> o .: "stability"
      <*> o .: "snap_id"
      <*> o .:? "parent_id"
      <*> o .: "timestamp"
      <*> o .:? "label"
      <*> o .:? "agent"
      <*> o .: "classification"
      <*> o .: "repo_f_r"
      <*> o .:? "repo_f_wcg"
      <*> o .:? "repo_f_wdf"
      <*> o .: "files"
      <*> o .: "changed_files"
      <*> o .: "recommended_tests"
      <*> o .: "elapsed_ms"

-- | Compact line entry appended to @.canontra/snaps/ledger.jsonl@.
data LedgerEntry = LedgerEntry
  { leSnapId         :: !Text
  , leParentId       :: !(Maybe Text)
  , leTimestamp      :: !Text
  , leLabel          :: !(Maybe Text)
  , leAgent          :: !(Maybe Text)
  , leClassification :: !SnapClassification
  , leRepoFR         :: !Text
  , leFileCount      :: !Int
  , leChangedCount   :: !Int
  , leElapsedMs      :: !Double
  } deriving stock (Eq, Show, Generic)
    deriving anyclass (NFData)

instance ToJSON LedgerEntry where
  toJSON e = object
    [ "snap_id"        .= leSnapId e
    , "parent_id"      .= leParentId e
    , "timestamp"      .= leTimestamp e
    , "label"          .= leLabel e
    , "agent"          .= leAgent e
    , "classification" .= leClassification e
    , "repo_f_r"       .= leRepoFR e
    , "file_count"     .= leFileCount e
    , "changed_count"  .= leChangedCount e
    , "elapsed_ms"     .= leElapsedMs e
    ]

instance FromJSON LedgerEntry where
  parseJSON = Aeson.withObject "LedgerEntry" $ \o ->
    LedgerEntry
      <$> o .: "snap_id"
      <*> o .:? "parent_id"
      <*> o .: "timestamp"
      <*> o .:? "label"
      <*> o .:? "agent"
      <*> o .: "classification"
      <*> o .: "repo_f_r"
      <*> o .: "file_count"
      <*> o .: "changed_count"
      <*> o .: "elapsed_ms"

-- ============================================================================
-- Path Layout & Validation Helpers
-- ============================================================================

canontraStateDir :: FilePath -> FilePath
canontraStateDir repoDir = repoDir </> ".canontra"

snapsRootDir :: FilePath -> FilePath
snapsRootDir repoDir = canontraStateDir repoDir </> "snaps"

objectsDir :: FilePath -> FilePath
objectsDir repoDir = snapsRootDir repoDir </> "objects"

manifestsDir :: FilePath -> FilePath
manifestsDir repoDir = snapsRootDir repoDir </> "manifests"

headFilePath :: FilePath -> FilePath
headFilePath repoDir = snapsRootDir repoDir </> "HEAD"

ledgerFilePath :: FilePath -> FilePath
ledgerFilePath repoDir = snapsRootDir repoDir </> "ledger.jsonl"

manifestFilePath :: FilePath -> Text -> FilePath
manifestFilePath repoDir snapId =
  manifestsDir repoDir </> (T.unpack snapId ++ ".json")

-- | Validate that a snapshot identifier contains only safe filename characters
-- (@[A-Za-z0-9_-]@) and bounded length, eliminating traversal risk.
isSafeSnapId :: Text -> Bool
isSafeSnapId sid =
  not (T.null sid)
    && T.length sid <= 128
    && T.all (\c -> isAlphaNum c || c == '_' || c == '-') sid

-- | Validate canonical 64-character SHA-256 hex digest.
isValidSha256Hex :: Text -> Bool
isValidSha256Hex txt =
  T.length txt == 64 && T.all isHexDigit txt

-- | Validate that a workspace-relative POSIX path cannot traverse outside root.
isSafeRelativeFilePath :: FilePath -> Bool
isSafeRelativeFilePath fp
  | null fp = False
  | any (== '\0') fp = False
  | head fp == '/' || head fp == '\\' = False
  | otherwise =
      let dirs = splitDirectories (map (\c -> if c == '\\' then '/' else c) fp)
      in not (null dirs)
           && all (\seg -> seg /= ".." && seg /= ".") dirs
           && not (any (':' `elem`) dirs)

-- | Compute sharded content-addressed blob path (@objects/<ab>/<rest>@).
objectBlobPath :: FilePath -> Text -> Maybe FilePath
objectBlobPath repoDir f0Hex
  | not (isValidSha256Hex f0Hex) = Nothing
  | otherwise =
      let lowerHex = T.toLower f0Hex
          dirPart = T.unpack (T.take 2 lowerHex)
          filePart = T.unpack (T.drop 2 lowerHex)
      in Just (objectsDir repoDir </> dirPart </> filePart)

getCurrentPidString :: IO String
getCurrentPidString = do
  pid <- c_getpid
  pure (show pid)

-- ============================================================================
-- Store Initialization & Atomic I/O
-- ============================================================================

-- | Initialize @.canontra/snaps/{objects,manifests}@ and drop a protective
-- @.canontra/.gitignore@ so AI snap/cache state is never accidentally committed.
ensureSnapStore :: FilePath -> IO ()
ensureSnapStore repoDir = do
  createDirectoryIfMissing True (objectsDir repoDir)
  createDirectoryIfMissing True (manifestsDir repoDir)
  let giPath = canontraStateDir repoDir </> ".gitignore"
  exists <- doesFileExist giPath
  if exists
    then pure ()
    else writeFile giPath "# Generated by Canontra — do not commit local cache or snap state\n*\n"

-- | Read the active @snap_id@ pointed to by @.canontra/snaps/HEAD@.
readHeadSnapId :: FilePath -> IO (Maybe Text)
readHeadSnapId repoDir = do
  let hp = headFilePath repoDir
  exists <- doesFileExist hp
  if not exists
    then pure Nothing
    else do
      eBytes <- try (BS.readFile hp) :: IO (Either IOException BS.ByteString)
      case eBytes of
        Left _ -> pure Nothing
        Right raw ->
          let sid = T.strip (TE.decodeUtf8Lenient raw)
          in if isSafeSnapId sid then pure (Just sid) else pure Nothing

-- | Atomically update @.canontra/snaps/HEAD@.
writeHeadSnapId :: FilePath -> Text -> IO ()
writeHeadSnapId repoDir sid = do
  let hp = headFilePath repoDir
  pidStr <- getCurrentPidString
  let tmp = hp ++ ".tmp." ++ pidStr
  BS.writeFile tmp (TE.encodeUtf8 (sid <> "\n"))
  atomicSwapWithRetry_ tmp hp

-- | Store raw bytes into content-addressed @objects/<ab>/<rest>@ only if absent.
-- Returns 'True' when a new blob was written and 'False' on deduplicated skip.
storeBlobIfAbsent :: FilePath -> Text -> BS.ByteString -> IO Bool
storeBlobIfAbsent repoDir f0Hex rawBytes =
  case objectBlobPath repoDir f0Hex of
    Nothing -> pure False
    Just blobPath -> do
      exists <- doesFileExist blobPath
      if exists
        then pure False
        else do
          createDirectoryIfMissing True (takeDirectory blobPath)
          pidStr <- getCurrentPidString
          let tmp = blobPath ++ ".tmp." ++ pidStr
          BS.writeFile tmp rawBytes
          atomicSwapWithRetry_ tmp blobPath
          pure True

-- | Read a stored blob and verify its SHA-256 matches @expectedF0@ before returning.
readVerifiedBlob :: FilePath -> Text -> IO (Either String BS.ByteString)
readVerifiedBlob repoDir expectedF0 =
  case objectBlobPath repoDir expectedF0 of
    Nothing -> pure (Left ("Invalid SHA-256 blob key: " ++ T.unpack expectedF0))
    Just blobPath -> do
      exists <- doesFileExist blobPath
      if not exists
        then pure (Left ("Missing blob in .canontra/snaps/objects for digest " ++ T.unpack expectedF0))
        else do
          eBytes <- try (BS.readFile blobPath) :: IO (Either IOException BS.ByteString)
          case eBytes of
            Left err -> pure (Left ("Failed reading blob " ++ blobPath ++ ": " ++ show err))
            Right rawBytes ->
              let actualF0 = T.toLower (unFingerprint (computeF0 rawBytes))
                  normExpected = T.toLower expectedF0
              in if actualF0 == normExpected
                   then pure (Right rawBytes)
                   else pure (Left ("SHA-256 verification failed for blob " ++ T.unpack expectedF0
                                    ++ " (computed " ++ T.unpack actualF0 ++ ")"))

-- | Atomically persist a 'SnapManifest' JSON document.
writeSnapManifest :: FilePath -> SnapManifest -> IO ()
writeSnapManifest repoDir manifest = do
  let mp = manifestFilePath repoDir (smSnapId manifest)
  createDirectoryIfMissing True (takeDirectory mp)
  pidStr <- getCurrentPidString
  let tmp = mp ++ ".tmp." ++ pidStr
  LBS.writeFile tmp (AesonPretty.encodePretty manifest)
  atomicSwapWithRetry_ tmp mp

-- | List all valid snapshot IDs sorted lexicographically.
listAllManifestIds :: FilePath -> IO [Text]
listAllManifestIds repoDir = do
  let mDir = manifestsDir repoDir
  eEntries <- try (listDirectory mDir) :: IO (Either IOException [FilePath])
  case eEntries of
    Left _ -> pure []
    Right entries ->
      pure $ sort
        [ T.pack stem
        | f <- entries
        , takeExtension f == ".json"
        , let stem = dropExtension f
        , isSafeSnapId (T.pack stem)
        ]

-- | Resolve @"HEAD"@, @"latest"@, an exact @snap_id@, or a unique prefix to a canonical @snap_id@.
resolveSnapId :: FilePath -> Text -> IO (Either String Text)
resolveSnapId repoDir rawRef
  | rawRef == "HEAD" || rawRef == "latest" = do
      mHead <- readHeadSnapId repoDir
      case mHead of
        Just sid -> pure (Right sid)
        Nothing  -> pure (Left "No snapshot HEAD found. Run 'canontra snap init' first.")
  | not (isSafeSnapId rawRef) =
      pure (Left ("Security/validation error: unsafe snapshot identifier '" ++ T.unpack rawRef ++ "'"))
  | otherwise = do
      let exactPath = manifestFilePath repoDir rawRef
      exactExists <- doesFileExist exactPath
      if exactExists
        then pure (Right rawRef)
        else do
          allIds <- listAllManifestIds repoDir
          let matches = filter (T.unpack rawRef `isPrefixOf`) (map T.unpack allIds)
          case matches of
            [unique] -> pure (Right (T.pack unique))
            [] -> pure (Left ("Snapshot not found: '" ++ T.unpack rawRef ++ "'"))
            manyMatches ->
              pure (Left ("Ambiguous snapshot prefix '" ++ T.unpack rawRef ++ "' matches: "
                          ++ unwords (take 5 manyMatches)))

-- | Resolve and decode a 'SnapManifest'.
readSnapManifest :: FilePath -> Text -> IO (Either String SnapManifest)
readSnapManifest repoDir ref = do
  eSid <- resolveSnapId repoDir ref
  case eSid of
    Left err  -> pure (Left err)
    Right sid -> readSnapManifestDirect repoDir sid

-- | Read and decode a manifest by exact validated @snap_id@.
readSnapManifestDirect :: FilePath -> Text -> IO (Either String SnapManifest)
readSnapManifestDirect repoDir sid
  | not (isSafeSnapId sid) = pure (Left ("Unsafe snapshot identifier: " ++ T.unpack sid))
  | otherwise = do
      let mp = manifestFilePath repoDir sid
      eBytes <- try (LBS.readFile mp) :: IO (Either IOException LBS.ByteString)
      case eBytes of
        Left err -> pure (Left ("Failed reading manifest " ++ mp ++ ": " ++ show err))
        Right lbs ->
          case Aeson.eitherDecode lbs of
            Left decErr -> pure (Left ("Corrupt snapshot manifest " ++ mp ++ ": " ++ decErr))
            Right m     -> pure (Right m)

-- | Append a compact JSON line to @.canontra/snaps/ledger.jsonl@.
appendLedgerEntry :: FilePath -> LedgerEntry -> IO ()
appendLedgerEntry repoDir entry = do
  let lp = ledgerFilePath repoDir
      lineBS = LBS.toStrict (Aeson.encode entry <> "\n")
  BS.appendFile lp lineBS

-- | Read all valid ledger entries in chronological append order.
readLedgerEntries :: FilePath -> IO [LedgerEntry]
readLedgerEntries repoDir = do
  let lp = ledgerFilePath repoDir
  exists <- doesFileExist lp
  if not exists
    then pure []
    else do
      eBytes <- try (LBS.readFile lp) :: IO (Either IOException LBS.ByteString)
      case eBytes of
        Left _ -> pure []
        Right lbs ->
          pure $ mapMaybe decodeLine (LBSC.lines lbs)
  where
    decodeLine line
      | LBS.null line = Nothing
      | otherwise     = Aeson.decode line

-- | Safely remove a manifest JSON file by exact validated ID.
removeManifestFile :: FilePath -> Text -> IO ()
removeManifestFile repoDir sid
  | not (isSafeSnapId sid) = pure ()
  | otherwise = do
      let mp = manifestFilePath repoDir sid
      exists <- doesFileExist mp
      if exists then removeFile mp else pure ()