packages feed

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

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

{- |
Module      : Canontra.Harness.SubVersion
Description : Stateless AI harness semantic sub-versioning engine (@canontra snap@).

Implements zero-daemon, zero-.git-mutation semantic checkpoints and recovery:
  - @snapInit@:   capture baseline @snap_0@ under @.canontra/snaps/@
  - @snapMark@:   incremental warm scan (< 25 ms target) + 9-tier semantic classification
  - @snapDiff@:   token-compact 3-level delta + symbol diff + blast-radius test slicing
  - @snapRewind@: preflight SHA-256 + path-containment verified atomic workspace rollback
  - @snapLog@:    chronological turn history inspection
  - @snapGC@:     mark-and-sweep garbage collection over unreferenced @F0@ blobs
-}
module Canontra.Harness.SubVersion
  ( -- * Report Types
    SnapSymbolChange (..)
  , SnapDiffReport (..)
  , SnapRewindReport (..)
  , SnapGCReport (..)

    -- * Core Delta & Classification Functions
  , allTierNames
  , diffFileBundles
  , computeFileDeltas
  , classifySnapDeltas
  , scanWorkspaceRecords
  , recommendTestsForDeltas
  , toRunnableTestCommand

    -- * Harness Operations
  , snapInit
  , snapMark
  , snapDiff
  , snapRewind
  , snapLog
  , snapGC

    -- * Human & JSON Formatting
  , formatSnapManifest
  , formatSnapManifestJson
  , formatSnapDiff
  , formatSnapDiffJson
  , formatSnapRewind
  , formatSnapRewindJson
  , formatSnapLog
  , formatSnapLogJson
  , formatSnapGC
  , formatSnapGCJson
  ) where

import Control.DeepSeq (NFData)
import Control.Exception (IOException, try)
import Control.Monad (forM, when)
import Data.Aeson (ToJSON (..), object, (.=))
import qualified Data.Aeson.Encode.Pretty as AesonPretty
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import Data.List (sort)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock (getCurrentTime)
import Data.Time.Format (defaultTimeLocale, formatTime)
import GHC.Clock (getMonotonicTimeNSec)
import GHC.Generics (Generic)
import System.Directory
  ( createDirectoryIfMissing
  , doesDirectoryExist
  , doesFileExist
  , getFileSize
  , listDirectory
  , removeFile
  )
import System.FilePath ((</>), takeDirectory, takeExtension)
import Text.Printf (printf)

import Canontra.Analysis.Impact (findMatchingTests)
import Canontra.Analysis.WholeRepoGraph (buildWholeRepoCallGraphFromSummaries)
import Canontra.Cache.Common (atomicSwapWithRetry_)
import Canontra.Cache.MerkleCache (defaultCachePath)
import Canontra.Cache.SlabV7 (SlabV7Entry (..), readAnySlabCacheForV7)
import Canontra.Comparison.Diff (DeclDiff (..), DiffResult (..), diffPrograms)
import Canontra.Fingerprint.Source (computeF0)
import Canontra.Harness.Store
import Canontra.IR.Program (Module (..), Program (..))
import Canontra.Normalize.Rules (snapSchemaVersion, snapStability)
import Canontra.Parser.Polyglot (parsePolyglotByteString)
import Canontra.Repository.Repository
  ( fingerprintDirectoryWithCache
  , normalizePathPosix
  )
import Canontra.Security.Path (canonicalizeSafePath)
import Canontra.Types
  ( FileEntry (..)
  , Fingerprint (..)
  , FingerprintBundle (..)
  , ParseError (..)
  , RepositoryManifest (..)
  , WholeRepoCallEdge (..)
  , WholeRepoCallGraph (..)
  , symFilePath
  )

-- | Symbol-level change extracted between two snapshots using 'diffPrograms'.
data SnapSymbolChange = SnapSymbolChange
  { sscFile   :: !FilePath
  , sscAction :: !Text
  , sscSymbol :: !Text
  , sscDetail :: !Text
  } deriving stock (Eq, Ord, Show, Generic)
    deriving anyclass (NFData)

instance ToJSON SnapSymbolChange where
  toJSON s = object
    [ "file"   .= sscFile s
    , "action" .= sscAction s
    , "symbol" .= sscSymbol s
    , "detail" .= sscDetail s
    ]

-- | Semantic delta report produced by @canontra snap diff@.
data SnapDiffReport = SnapDiffReport
  { sdrSchemaVersion    :: !Text
  , sdrStability        :: !Text
  , sdrFromSnap         :: !Text
  , sdrToSnap           :: !Text
  , sdrClassification   :: !SnapClassification
  , sdrCompact          :: !Bool
  , sdrLevel1Trivia     :: ![SnapFileDelta]
  , sdrLevel2Logic      :: ![SnapFileDelta]
  , sdrLevel3Contract   :: ![SnapFileDelta]
  , sdrSymbolChanges    :: ![SnapSymbolChange]
  , sdrRecommendedTests :: ![Text]
  , sdrElapsedMs        :: !Double
  } deriving stock (Eq, Show, Generic)
    deriving anyclass (NFData)

instance ToJSON SnapDiffReport where
  toJSON r = object
    [ "schema_version"    .= sdrSchemaVersion r
    , "stability"         .= sdrStability r
    , "from_snap"         .= sdrFromSnap r
    , "to_snap"           .= sdrToSnap r
    , "classification"    .= sdrClassification r
    , "compact"           .= sdrCompact r
    , "level1_trivia"     .= if sdrCompact r then ([] :: [SnapFileDelta]) else sdrLevel1Trivia r
    , "level1_count"      .= length (sdrLevel1Trivia r)
    , "level2_logic"      .= sdrLevel2Logic r
    , "level3_contract"   .= sdrLevel3Contract r
    , "symbol_changes"    .= sdrSymbolChanges r
    , "recommended_tests" .= sdrRecommendedTests r
    , "elapsed_ms"        .= sdrElapsedMs r
    ]

-- | Workspace restoration report emitted by @canontra snap rewind@.
data SnapRewindReport = SnapRewindReport
  { srrSchemaVersion :: !Text
  , srrStability     :: !Text
  , srrTargetSnapId  :: !Text
  , srrDryRun        :: !Bool
  , srrRestoredFiles :: ![FilePath]
  , srrRemovedFiles  :: ![FilePath]
  , srrUnchangedSkip :: !Int
  , srrElapsedMs     :: !Double
  } deriving stock (Eq, Show, Generic)
    deriving anyclass (NFData)

instance ToJSON SnapRewindReport where
  toJSON r = object
    [ "schema_version"  .= srrSchemaVersion r
    , "stability"       .= srrStability r
    , "target_snap_id"  .= srrTargetSnapId r
    , "dry_run"         .= srrDryRun r
    , "restored_files"  .= srrRestoredFiles r
    , "removed_files"   .= srrRemovedFiles r
    , "unchanged_files" .= srrUnchangedSkip r
    , "elapsed_ms"      .= srrElapsedMs r
    ]

-- | Garbage collection report emitted by @canontra snap gc@.
data SnapGCReport = SnapGCReport
  { gcrSchemaVersion   :: !Text
  , gcrStability       :: !Text
  , gcrRetainedSnaps   :: !Int
  , gcrPrunedSnaps     :: !Int
  , gcrLiveBlobs       :: !Int
  , gcrRemovedBlobs    :: !Int
  , gcrReclaimedBytes  :: !Integer
  } deriving stock (Eq, Show, Generic)
    deriving anyclass (NFData)

instance ToJSON SnapGCReport where
  toJSON r = object
    [ "schema_version"  .= gcrSchemaVersion r
    , "stability"       .= gcrStability r
    , "retained_snaps"  .= gcrRetainedSnaps r
    , "pruned_snaps"    .= gcrPrunedSnaps r
    , "live_blobs"      .= gcrLiveBlobs r
    , "removed_blobs"   .= gcrRemovedBlobs r
    , "reclaimed_bytes" .= gcrReclaimedBytes r
    ]

-- ============================================================================
-- 9-Tier Semantic Delta & Classification
-- ============================================================================

-- | Ordered list of all 9 Canontra fingerprint tier names.
allTierNames :: [Text]
allTierNames = ["F0", "F1", "F2", "F3", "F_CG", "F_CF", "F_DF", "F_T", "F4"]

-- | Compare two 'FingerprintBundle' values returning @(mutated, invariant, severity)@.
diffFileBundles :: FingerprintBundle -> FingerprintBundle -> ([Text], [Text], Text)
diffFileBundles bOld bNew =
  let checks =
        [ ("F0",   f0Source bOld /= f0Source bNew)
        , ("F1",   f1Structural bOld /= f1Structural bNew)
        , ("F2",   f2Declaration bOld /= f2Declaration bNew)
        , ("F3",   f3Dependency bOld /= f3Dependency bNew)
        , ("F_CG", fCGCallGraph bOld /= fCGCallGraph bNew)
        , ("F_CF", fCFControlFlow bOld /= fCFControlFlow bNew)
        , ("F_DF", fDFDataFlow bOld /= fDFDataFlow bNew)
        , ("F_T",  fTTypeContract bOld /= fTTypeContract bNew)
        , ("F4",   f4Composite bOld /= f4Composite bNew)
        ]
      mutated   = [name | (name, True)  <- checks]
      invariant = [name | (name, False) <- checks]
      hasContract = any (\t -> t == "F2" || t == "F3" || t == "F_T") mutated
      hasLogic = any (\t -> t == "F1" || t == "F_CG" || t == "F_CF" || t == "F_DF" || t == "F4") mutated
      severity
        | hasContract = "Level3_Contract"
        | hasLogic    = "Level2_Logic"
        | otherwise   = "Level1_Trivia"
  in (mutated, invariant, severity)

-- | Compute deterministic sorted per-file deltas between two snapshot maps.
computeFileDeltas
  :: Map FilePath SnapFileRecord
  -> Map FilePath SnapFileRecord
  -> [SnapFileDelta]
computeFileDeltas oldMap newMap =
  let allPaths = Set.toAscList (Set.union (Map.keysSet oldMap) (Map.keysSet newMap))
  in foldr step [] allPaths
  where
    step p acc = case (Map.lookup p oldMap, Map.lookup p newMap) of
      (Nothing, Just _) ->
        SnapFileDelta p "added" "Level3_Contract" allTierNames [] : acc
      (Just _, Nothing) ->
        SnapFileDelta p "deleted" "Level3_Contract" allTierNames [] : acc
      (Just rOld, Just rNew)
        | sfrF0 rOld == sfrF0 rNew && sfrBundle rOld == sfrBundle rNew -> acc
        | otherwise ->
            let (muts, invs, sev) = diffFileBundles (sfrBundle rOld) (sfrBundle rNew)
            in SnapFileDelta p "modified" sev muts invs : acc
      (Nothing, Nothing) -> acc

-- | Collapse per-file deltas into an overall snapshot classification.
classifySnapDeltas :: [SnapFileDelta] -> SnapClassification
classifySnapDeltas [] = SnapNoChange
classifySnapDeltas deltas
  | any (\d -> sfdSeverity d == "Level3_Contract") deltas = SnapContractChange
  | any (\d -> sfdSeverity d == "Level2_Logic") deltas    = SnapInternalLogic
  | otherwise                                             = SnapSemanticNoop

-- | Scan the workspace using the warm @CNTR\\x07@ slab cache and build normalized records.
scanWorkspaceRecords
  :: FilePath
  -> IO (Either String (RepositoryManifest, Map FilePath SnapFileRecord))
scanWorkspaceRecords repoDir = do
  res <- fingerprintDirectoryWithCache repoDir True
  case res of
    Left err -> pure (Left ("Parse error in " ++ peFile err ++ ": " ++ T.unpack (peReason err)))
    Right manifest -> do
      pairs <- forM (rmFiles manifest) $ \fe -> do
        let rel = normalizePathPosix (fePath fe)
            fullPath = repoDir </> rel
        eSz <- try (getFileSize fullPath) :: IO (Either IOException Integer)
        let sz = either (const 0) id eSz
            b = feFingerprints fe
        pure (rel, SnapFileRecord rel (unFingerprint (f0Source b)) sz b)
      pure (Right (manifest, Map.fromList pairs))

-- | Compute runnable test recommendations for a set of deltas using cached @CNTR\\x07@
-- summaries (for contract-level transitive expansion) + fast basename test matching.
recommendTestsForDeltas :: FilePath -> [FilePath] -> [SnapFileDelta] -> IO [Text]
recommendTestsForDeltas repoDir allFiles deltas = do
  let logicOrContract = [sfdPath d | d <- deltas, sfdSeverity d /= "Level1_Trivia"]
      contractPaths   = [sfdPath d | d <- deltas, sfdSeverity d == "Level3_Contract"]
  if null logicOrContract
    then pure []
    else do
      expandedAffected <- if null contractPaths
        then pure logicOrContract
        else expandContractCallers repoDir logicOrContract contractPaths
      let rawTests = findMatchingTests expandedAffected allFiles
      pure $ Set.toAscList (Set.fromList (map toRunnableTestCommand rawTests))

expandContractCallers :: FilePath -> [FilePath] -> [FilePath] -> IO [FilePath]
expandContractCallers repoDir baseAffected contractPaths = do
  let cachePath = defaultCachePath repoDir
  exists <- doesFileExist cachePath
  if not exists
    then pure baseAffected
    else do
      eBytes <- try (BS.readFile cachePath) :: IO (Either IOException BS.ByteString)
      case eBytes of
        Left _ -> pure baseAffected
        Right bs -> case readAnySlabCacheForV7 bs of
          Just (entryMap, _) ->
            let summaries = [sm | e <- Map.elems entryMap, Just sm <- [sv7Summary e]]
            in if null summaries
                 then pure baseAffected
                 else
                   let wcg = buildWholeRepoCallGraphFromSummaries summaries
                       targetSet = Set.fromList (map normalizePathPosix contractPaths)
                       callers =
                         [ normalizePathPosix (symFilePath (wceCaller e))
                         | e <- wcgEdges wcg
                         , Set.member (normalizePathPosix (symFilePath (wceCallee e))) targetSet
                         ]
                   in pure (Set.toAscList (Set.fromList (baseAffected ++ callers)))
          Nothing -> pure baseAffected

-- | Format a discovered test path into an actionable runner invocation when unambiguous.
toRunnableTestCommand :: FilePath -> Text
toRunnableTestCommand fp =
  let norm = normalizePathPosix fp
      ext = map toLowerAscii (takeExtension norm)
  in case ext of
       ".py" -> "pytest " <> T.pack norm
       ".ts" -> "npx jest " <> T.pack norm
       ".tsx" -> "npx jest " <> T.pack norm
       ".js" -> "npx jest " <> T.pack norm
       ".jsx" -> "npx jest " <> T.pack norm
       ".go" ->
         let dir = takeDirectory norm
         in if dir == "." || null dir
              then "go test ./..."
              else "go test ./" <> T.pack dir
       ".rs" -> "cargo test"
       _     -> T.pack norm
  where
    toLowerAscii c
      | c >= 'A' && c <= 'Z' = toEnum (fromEnum c + 32)
      | otherwise            = c

elapsedMsSince :: Integral a => a -> a -> Double
elapsedMsSince startNs endNs =
  fromIntegral (toInteger endNs - toInteger startNs) / 1000000.0

formatUtcTimestamp :: IO (Text, Text)
formatUtcTimestamp = do
  now <- getCurrentTime
  let isoTxt = T.pack (formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ" now)
      compactTxt = T.pack (formatTime defaultTimeLocale "%Y%m%dT%H%M%S%3qZ" now)
  pure (isoTxt, compactTxt)

makeLedgerEntry :: SnapManifest -> LedgerEntry
makeLedgerEntry m = LedgerEntry
  { leSnapId         = smSnapId m
  , leParentId       = smParentId m
  , leTimestamp      = smTimestamp m
  , leLabel          = smLabel m
  , leAgent          = smAgent m
  , leClassification = smClassification m
  , leRepoFR         = smRepoFR m
  , leFileCount      = Map.size (smFiles m)
  , leChangedCount   = length (smChangedFiles m)
  , leElapsedMs      = smElapsedMs m
  }

-- ============================================================================
-- Sub-Versioning Operations
-- ============================================================================

-- | Initialize @.canontra/snaps/@ and capture baseline @snap_0@.
snapInit :: FilePath -> IO (Either String SnapManifest)
snapInit repoDir = do
  t0 <- getMonotonicTimeNSec
  ensureSnapStore repoDir
  eScan <- scanWorkspaceRecords repoDir
  case eScan of
    Left err -> pure (Left err)
    Right (repoMan, fileRecords) -> do
      _ <- storeChangedBlobs repoDir Map.empty fileRecords
      (isoTs, _) <- formatUtcTimestamp
      t1 <- getMonotonicTimeNSec
      let !elapsed = elapsedMsSince t0 t1
          manifest = SnapManifest
            { smSchemaVersion    = snapSchemaVersion
            , smStability        = snapStability
            , smSnapId           = "snap_0"
            , smParentId         = Nothing
            , smTimestamp        = isoTs
            , smLabel            = Just "baseline"
            , smAgent            = Nothing
            , smClassification   = SnapNoChange
            , smRepoFR           = unFingerprint (rmRepositoryFingerprint repoMan)
            , smRepoFWCG         = fmap unFingerprint (rmWholeRepoCallGraph repoMan)
            , smRepoFWDF         = fmap unFingerprint (rmWholeRepoDataFlow repoMan)
            , smFiles            = fileRecords
            , smChangedFiles     = []
            , smRecommendedTests = []
            , smElapsedMs        = elapsed
            }
      writeSnapManifest repoDir manifest
      writeHeadSnapId repoDir "snap_0"
      appendLedgerEntry repoDir (makeLedgerEntry manifest)
      pure (Right manifest)

-- | Capture an incremental checkpoint comparing against @HEAD@.
-- When @skipNoop@ is 'True' and classification is 'SnapNoChange', returns
-- @Right (parentManifest, True)@ without writing a new snapshot.
snapMark
  :: FilePath
  -> Maybe Text
  -> Maybe Text
  -> Bool
  -> IO (Either String (SnapManifest, Bool))
snapMark repoDir mLabel mAgent skipNoop = do
  t0 <- getMonotonicTimeNSec
  mHeadId <- readHeadSnapId repoDir
  case mHeadId of
    Nothing ->
      pure (Left "Snap store is not initialized in this workspace. Run 'canontra snap init' first.")
    Just parentId -> do
      eParent <- readSnapManifestDirect repoDir parentId
      case eParent of
        Left err -> pure (Left err)
        Right parentMan -> do
          eScan <- scanWorkspaceRecords repoDir
          case eScan of
            Left err -> pure (Left err)
            Right (repoMan, newRecords) -> do
              let deltas = computeFileDeltas (smFiles parentMan) newRecords
                  classification = classifySnapDeltas deltas
              if skipNoop && classification == SnapNoChange
                then pure (Right (parentMan, True))
                else do
                  ensureSnapStore repoDir
                  _ <- storeChangedBlobs repoDir (smFiles parentMan) newRecords
                  recTests <- recommendTestsForDeltas repoDir (Map.keys newRecords) deltas
                  (isoTs, compactTs) <- formatUtcTimestamp
                  let frHex = unFingerprint (rmRepositoryFingerprint repoMan)
                      baseId = "snap_" <> compactTs <> "_" <> T.take 8 frHex
                  snapId <- ensureUniqueSnapId repoDir baseId
                  t1 <- getMonotonicTimeNSec
                  let !elapsed = elapsedMsSince t0 t1
                      manifest = SnapManifest
                        { smSchemaVersion    = snapSchemaVersion
                        , smStability        = snapStability
                        , smSnapId           = snapId
                        , smParentId         = Just parentId
                        , smTimestamp        = isoTs
                        , smLabel            = mLabel
                        , smAgent            = mAgent
                        , smClassification   = classification
                        , smRepoFR           = frHex
                        , smRepoFWCG         = fmap unFingerprint (rmWholeRepoCallGraph repoMan)
                        , smRepoFWDF         = fmap unFingerprint (rmWholeRepoDataFlow repoMan)
                        , smFiles            = newRecords
                        , smChangedFiles     = deltas
                        , smRecommendedTests = recTests
                        , smElapsedMs        = elapsed
                        }
                  writeSnapManifest repoDir manifest
                  writeHeadSnapId repoDir snapId
                  appendLedgerEntry repoDir (makeLedgerEntry manifest)
                  pure (Right (manifest, False))

ensureUniqueSnapId :: FilePath -> Text -> IO Text
ensureUniqueSnapId repoDir candidate = go (0 :: Int) candidate
  where
    go n cur = do
      exists <- doesFileExist (manifestFilePath repoDir cur)
      if not exists
        then pure cur
        else let nextN = n + 1
             in go nextN (candidate <> "_" <> T.pack (show nextN))

storeChangedBlobs
  :: FilePath
  -> Map FilePath SnapFileRecord
  -> Map FilePath SnapFileRecord
  -> IO Int
storeChangedBlobs repoDir oldMap newMap = do
  results <- forM (Map.toList newMap) $ \(relPath, rec) ->
    case Map.lookup relPath oldMap of
      Just oldRec | sfrF0 oldRec == sfrF0 rec -> do
        -- Ensure blob still exists even if hash matched
        case objectBlobPath repoDir (sfrF0 rec) of
          Just bp -> do
            exists <- doesFileExist bp
            if exists
              then pure 0
              else writeFromDisk relPath (sfrF0 rec)
          Nothing -> pure 0
      _ -> writeFromDisk relPath (sfrF0 rec)
  pure (sum results)
  where
    writeFromDisk relPath f0Hex = do
      let fullPath = repoDir </> relPath
      eBytes <- try (BS.readFile fullPath) :: IO (Either IOException BS.ByteString)
      case eBytes of
        Left _ -> pure 0
        Right raw -> do
          let actualF0 = unFingerprint (computeF0 raw)
          wrote <- storeBlobIfAbsent repoDir actualF0 raw
          when (actualF0 /= f0Hex) $
            storeBlobIfAbsent repoDir f0Hex raw >> pure ()
          pure (if wrote then 1 else 0)

-- | Compare two snapshots (or @WORKTREE@) returning partitioned semantic deltas,
-- symbol-level changes, and affected test commands.
snapDiff :: FilePath -> Text -> Text -> Bool -> IO (Either String SnapDiffReport)
snapDiff repoDir refA refB compact = do
  t0 <- getMonotonicTimeNSec
  eA <- loadSide refA
  case eA of
    Left err -> pure (Left err)
    Right (idA, mapA, isWorktreeA) -> do
      eB <- loadSide refB
      case eB of
        Left err -> pure (Left err)
        Right (idB, mapB, isWorktreeB) -> do
          let deltas = computeFileDeltas mapA mapB
              classification = classifySnapDeltas deltas
              l1 = [d | d <- deltas, sfdSeverity d == "Level1_Trivia"]
              l2 = [d | d <- deltas, sfdSeverity d == "Level2_Logic"]
              l3 = [d | d <- deltas, sfdSeverity d == "Level3_Contract"]
              allKnownFiles = Set.toAscList (Set.union (Map.keysSet mapA) (Map.keysSet mapB))
          recTests <- recommendTestsForDeltas repoDir allKnownFiles deltas
          symChanges <- extractSymbolChanges repoDir mapA mapB isWorktreeA isWorktreeB (l2 ++ l3)
          t1 <- getMonotonicTimeNSec
          pure $ Right SnapDiffReport
            { sdrSchemaVersion    = snapSchemaVersion
            , sdrStability        = snapStability
            , sdrFromSnap         = idA
            , sdrToSnap           = idB
            , sdrClassification   = classification
            , sdrCompact          = compact
            , sdrLevel1Trivia     = l1
            , sdrLevel2Logic      = l2
            , sdrLevel3Contract   = l3
            , sdrSymbolChanges    = symChanges
            , sdrRecommendedTests = recTests
            , sdrElapsedMs        = elapsedMsSince t0 t1
            }
  where
    loadSide ref
      | ref == "WORKTREE" || ref == "worktree" = do
          eScan <- scanWorkspaceRecords repoDir
          pure (fmap (\(_, recs) -> ("WORKTREE", recs, True)) eScan)
      | otherwise = do
          eMan <- readSnapManifest repoDir ref
          pure (fmap (\m -> (smSnapId m, smFiles m, False)) eMan)

extractSymbolChanges
  :: FilePath
  -> Map FilePath SnapFileRecord
  -> Map FilePath SnapFileRecord
  -> Bool
  -> Bool
  -> [SnapFileDelta]
  -> IO [SnapSymbolChange]
extractSymbolChanges repoDir mapA mapB isWtA isWtB deltas = do
  nested <- forM deltas $ \d -> do
    let p = sfdPath d
    mOldProg <- loadSideProg isWtA (Map.lookup p mapA) p
    mNewProg <- loadSideProg isWtB (Map.lookup p mapB) p
    pure $ case (mOldProg, mNewProg) of
      (Just oldP, Just newP) ->
        [ SnapSymbolChange p (ddAction dd) (ddTarget dd) (ddDetails dd)
        | dd <- drDeclarationDiffs (diffPrograms oldP newP)
        ]
      (Nothing, Just newP) ->
        [ SnapSymbolChange p "added" (ddTarget dd) (ddDetails dd)
        | dd <- drDeclarationDiffs (diffPrograms (emptyProgLike newP) newP)
        ]
      (Just oldP, Nothing) ->
        [ SnapSymbolChange p "removed" (ddTarget dd) (ddDetails dd)
        | dd <- drDeclarationDiffs (diffPrograms oldP (emptyProgLike oldP))
        ]
      (Nothing, Nothing) -> []
  pure (concat nested)
  where
    emptyProgLike (Program _ lang) = Program [Module "" [] [] []] lang

    loadSideProg _ Nothing _ = pure Nothing
    loadSideProg isWt (Just rec) relPath = do
      eBytes <- if isWt
        then do
          eRaw <- try (BS.readFile (repoDir </> relPath)) :: IO (Either IOException BS.ByteString)
          pure (either (Left . show) Right eRaw)
        else readVerifiedBlob repoDir (sfrF0 rec)
      case eBytes of
        Left _ -> pure Nothing
        Right raw -> case parsePolyglotByteString relPath raw of
          Left _     -> pure Nothing
          Right prog -> pure (Just prog)

-- | Preflight-verified atomic rollback to a target snapshot.
-- Validates path containment for every restored/removed file and SHA-256 verifies
-- every blob BEFORE touching any file in the working tree. Never deletes
-- unrelated untracked files.
snapRewind
  :: FilePath
  -> Text
  -> [FilePath]
  -> Bool
  -> IO (Either String SnapRewindReport)
snapRewind repoDir ref filesFilter dryRun = do
  t0 <- getMonotonicTimeNSec
  eTarget <- readSnapManifest repoDir ref
  case eTarget of
    Left err -> pure (Left err)
    Right targetMan -> do
      let normFilter = Set.fromList (map normalizePathPosix filesFilter)
          requestedFiles =
            if null filesFilter
              then Map.toList (smFiles targetMan)
              else
                [ (p, r)
                | (p, r) <- Map.toList (smFiles targetMan)
                , Set.member p normFilter
                ]
      -- Verify explicitly requested files all exist in target snapshot
      let missingFromTarget =
            [ f
            | f <- Set.toList normFilter
            , Map.notMember f (smFiles targetMan)
            ]
      if not (null filesFilter) && not (null missingFromTarget)
        then pure (Left ("Requested file(s) not present in snapshot "
                        ++ T.unpack (smSnapId targetMan) ++ ": " ++ unwords missingFromTarget))
        else do
          -- Identify tracked files from current HEAD that were created after target snap
          removeCandidates <- if not (null filesFilter)
            then pure []
            else do
              mHeadId <- readHeadSnapId repoDir
              case mHeadId of
                Nothing -> pure []
                Just headId -> do
                  eHeadMan <- readSnapManifestDirect repoDir headId
                  case eHeadMan of
                    Left _ -> pure []
                    Right headMan ->
                      pure
                        [ p
                        | p <- Map.keys (smFiles headMan)
                        , Map.notMember p (smFiles targetMan)
                        ]

          -- Step 1 (Preflight): Validate paths + verify blobs before ANY mutation
          ePlan <- preflightRewind requestedFiles removeCandidates
          case ePlan of
            Left err -> pure (Left err)
            Right (toWrite, toDelete, skippedCount) -> do
              when (not dryRun) $ do
                pidStr <- getCurrentPidString
                forM_ toWrite $ \(_, safeAbsPath, rawBytes) -> do
                  createDirectoryIfMissing True (takeDirectory safeAbsPath)
                  let tmp = safeAbsPath ++ ".tmp." ++ pidStr
                  BS.writeFile tmp rawBytes
                  atomicSwapWithRetry_ tmp safeAbsPath
                forM_ toDelete $ \(_, safeAbsPath) -> do
                  exists <- doesFileExist safeAbsPath
                  when exists (removeFile safeAbsPath)
                when (null filesFilter) $
                  writeHeadSnapId repoDir (smSnapId targetMan)

              t1 <- getMonotonicTimeNSec
              pure $ Right SnapRewindReport
                { srrSchemaVersion = snapSchemaVersion
                , srrStability     = snapStability
                , srrTargetSnapId  = smSnapId targetMan
                , srrDryRun        = dryRun
                , srrRestoredFiles = sort [p | (p, _, _) <- toWrite]
                , srrRemovedFiles  = sort [p | (p, _) <- toDelete]
                , srrUnchangedSkip = skippedCount
                , srrElapsedMs     = elapsedMsSince t0 t1
                }
  where
    forM_ = flip mapM_

    validateTargetPath relPath
      | not (isSafeRelativeFilePath relPath) =
          pure (Left ("Security violation: unsafe relative path in snapshot: " ++ relPath))
      | otherwise = do
          let absCand = repoDir </> relPath
          -- Check existing parent containment + full candidate containment
          eSafe <- canonicalizeSafePath repoDir absCand
          case eSafe of
            Left secErr -> pure (Left secErr)
            Right safeCand -> do
              let pDir = takeDirectory absCand
              dirExists <- doesDirectoryExist pDir
              if dirExists
                then do
                  eSafeDir <- canonicalizeSafePath repoDir pDir
                  case eSafeDir of
                    Left secErr -> pure (Left secErr)
                    Right _     -> pure (Right safeCand)
                else pure (Right safeCand)

    preflightRewind writeItems deleteItems = do
      wRes <- goWrites [] 0 writeItems
      case wRes of
        Left err -> pure (Left err)
        Right (writes, skips) -> do
          dRes <- goDeletes [] deleteItems
          case dRes of
            Left err -> pure (Left err)
            Right dels -> pure (Right (writes, dels, skips))

    goWrites acc !skips [] = pure (Right (reverse acc, skips))
    goWrites acc !skips ((relPath, rec) : rest) = do
      ePath <- validateTargetPath relPath
      case ePath of
        Left err -> pure (Left err)
        Right safeAbs -> do
          eBlob <- readVerifiedBlob repoDir (sfrF0 rec)
          case eBlob of
            Left err -> pure (Left err)
            Right rawBytes -> do
              onDisk <- try (BS.readFile safeAbs) :: IO (Either IOException BS.ByteString)
              let unchanged = case onDisk of
                    Right cur -> T.toLower (unFingerprint (computeF0 cur)) == T.toLower (sfrF0 rec)
                    Left _    -> False
              if unchanged
                then goWrites acc (skips + 1) rest
                else goWrites ((relPath, safeAbs, rawBytes) : acc) skips rest

    goDeletes acc [] = pure (Right (reverse acc))
    goDeletes acc (relPath : rest) = do
      ePath <- validateTargetPath relPath
      case ePath of
        Left err -> pure (Left err)
        Right safeAbs -> goDeletes ((relPath, safeAbs) : acc) rest

-- | Read snapshot ledger history (most recent first, bounded to @limit@).
snapLog :: FilePath -> Int -> IO (Either String (Maybe Text, [LedgerEntry]))
snapLog repoDir limitCount = do
  mHead <- readHeadSnapId repoDir
  entries <- readLedgerEntries repoDir
  let capped = if limitCount <= 0 then entries else take limitCount (reverse entries)
  pure (Right (mHead, capped))

-- | Garbage-collect manifests beyond the last @keepLast@ snapshots (always retaining
-- @HEAD@ and @snap_0@) and sweep unreferenced @F0@ blobs under @objects/@.
snapGC :: FilePath -> Int -> IO (Either String SnapGCReport)
snapGC repoDir keepLast = do
  mHead <- readHeadSnapId repoDir
  ledger <- readLedgerEntries repoDir
  allIds <- listAllManifestIds repoDir
  let recentIds = take (max 1 keepLast) (reverse (map leSnapId ledger))
      protected = Set.fromList ("snap_0" : maybe [] pure mHead ++ recentIds)
      pruneIds = filter (`Set.notMember` protected) allIds
      keepIds  = filter (`Set.member` protected) allIds
  mapM_ (removeManifestFile repoDir) pruneIds

  -- Collect live F0 hashes from retained manifests
  liveF0Lists <- forM keepIds $ \sid -> do
    eMan <- readSnapManifestDirect repoDir sid
    case eMan of
      Left _  -> pure []
      Right m -> pure [T.toLower (sfrF0 r) | r <- Map.elems (smFiles m)]
  let liveSet = Set.fromList (concat liveF0Lists)

  -- Walk 2-char object fanout buckets
  let oDir = objectsDir repoDir
  eBuckets <- try (listDirectory oDir) :: IO (Either IOException [FilePath])
  (removedCnt, reclaimed) <- case eBuckets of
    Left _ -> pure (0, 0)
    Right buckets -> do
      counts <- forM buckets $ \bucket -> do
        let bPath = oDir </> bucket
        isDir <- doesDirectoryExist bPath
        if not isDir || length bucket /= 2
          then pure (0, 0)
          else do
            eObjs <- try (listDirectory bPath) :: IO (Either IOException [FilePath])
            case eObjs of
              Left _ -> pure (0, 0)
              Right objs -> foldMObjects bPath bucket liveSet objs
      pure (sum (map fst counts), sum (map snd counts))

  pure $ Right SnapGCReport
    { gcrSchemaVersion  = snapSchemaVersion
    , gcrStability      = snapStability
    , gcrRetainedSnaps  = length keepIds
    , gcrPrunedSnaps    = length pruneIds
    , gcrLiveBlobs      = Set.size liveSet
    , gcrRemovedBlobs   = removedCnt
    , gcrReclaimedBytes = reclaimed
    }
  where
    foldMObjects bPath bucket liveSet objs = do
      res <- forM objs $ \objFile -> do
        let hexKey = T.pack (bucket ++ objFile)
            fullObj = bPath </> objFile
        if Set.member (T.toLower hexKey) liveSet
          then pure (0, 0)
          else do
            eSz <- try (getFileSize fullObj) :: IO (Either IOException Integer)
            _ <- try (removeFile fullObj) :: IO (Either IOException ())
            pure (1, either (const 0) id eSz)
      pure (sum (map fst res), sum (map snd res))

-- ============================================================================
-- Human & JSON Formatters
-- ============================================================================

formatDurationMs :: Double -> String
formatDurationMs ms = printf "%.2f ms" ms

formatSnapManifest :: Bool -> SnapManifest -> Text
formatSnapManifest skipped m =
  T.unlines $
    [ "================================================================================"
    , "  CANONTRA SNAP — SEMANTIC SUB-VERSIONING (" <> T.toUpper snapStability <> ")"
    , "================================================================================"
    , "  Snap ID:           " <> smSnapId m <> if skipped then " (unchanged — skipped new node)" else ""
    , "  Parent ID:         " <> maybe "null (baseline)" id (smParentId m)
    , "  Timestamp:         " <> smTimestamp m
    , "  Classification:    " <> classificationText (smClassification m)
    , "  Repo Hash (F_R):   " <> smRepoFR m
    , "  Tracked Files:     " <> T.pack (show (Map.size (smFiles m)))
    , "  Changed Files:     " <> T.pack (show (length (smChangedFiles m)))
    , "  Latency:           " <> T.pack (formatDurationMs (smElapsedMs m))
    ]
    ++ maybe [] (\l -> ["  Label:             " <> l]) (smLabel m)
    ++ maybe [] (\a -> ["  Agent:             " <> a]) (smAgent m)
    ++ (if null (smChangedFiles m)
          then []
          else
            [ "--------------------------------------------------------------------------------"
            , "  Changed Files:"
            ] ++
            [ "    [" <> sfdSeverity d <> "] " <> T.pack (sfdPath d)
                <> " (" <> sfdStatus d <> "; mutated: " <> T.intercalate "," (sfdMutatedTiers d) <> ")"
            | d <- smChangedFiles m
            ])
    ++ (if null (smRecommendedTests m)
          then []
          else
            [ "--------------------------------------------------------------------------------"
            , "  Recommended Tests:"
            ] ++ ["    " <> t | t <- smRecommendedTests m])
    ++ [ "================================================================================" ]

formatSnapManifestJson :: SnapManifest -> LBS.ByteString
formatSnapManifestJson = AesonPretty.encodePretty

formatSnapDiff :: Bool -> SnapDiffReport -> Text
formatSnapDiff compact r =
  T.unlines $
    [ "================================================================================"
    , "  CANONTRA SNAP DIFF (" <> T.toUpper snapStability <> ")"
    , "================================================================================"
    , "  From Snap:         " <> sdrFromSnap r
    , "  To Snap:           " <> sdrToSnap r
    , "  Classification:    " <> classificationText (sdrClassification r)
    , "  Level 3 Contract:  " <> T.pack (show (length (sdrLevel3Contract r))) <> " files"
    , "  Level 2 Logic:     " <> T.pack (show (length (sdrLevel2Logic r))) <> " files"
    , "  Level 1 Trivia:    " <> T.pack (show (length (sdrLevel1Trivia r))) <> " files"
        <> if compact then " (omitted in compact mode)" else ""
    , "  Latency:           " <> T.pack (formatDurationMs (sdrElapsedMs r))
    ]
    ++ renderSection "Level 3 (Contract / Dependency):" (sdrLevel3Contract r)
    ++ renderSection "Level 2 (Internal Logic):" (sdrLevel2Logic r)
    ++ (if compact then [] else renderSection "Level 1 (Formatting / Semantic No-op):" (sdrLevel1Trivia r))
    ++ (if null (sdrSymbolChanges r)
          then []
          else
            [ "--------------------------------------------------------------------------------"
            , "  Symbol Changes:"
            ] ++
            [ "    [" <> sscAction s <> "] " <> T.pack (sscFile s) <> "::" <> sscSymbol s <> " — " <> sscDetail s
            | s <- sdrSymbolChanges r
            ])
    ++ (if null (sdrRecommendedTests r)
          then []
          else
            [ "--------------------------------------------------------------------------------"
            , "  Recommended Tests:"
            ] ++ ["    " <> t | t <- sdrRecommendedTests r])
    ++ [ "================================================================================" ]
  where
    renderSection _ [] = []
    renderSection title xs =
      [ "--------------------------------------------------------------------------------"
      , "  " <> title
      ] ++
      [ "    " <> T.pack (sfdPath d) <> " (" <> sfdStatus d <> ": " <> T.intercalate "," (sfdMutatedTiers d) <> ")"
      | d <- xs
      ]

formatSnapDiffJson :: Bool -> SnapDiffReport -> LBS.ByteString
formatSnapDiffJson _ = AesonPretty.encodePretty

formatSnapRewind :: SnapRewindReport -> Text
formatSnapRewind r =
  T.unlines $
    [ "================================================================================"
    , "  CANONTRA SNAP REWIND" <> if srrDryRun r then " (DRY RUN)" else ""
    , "================================================================================"
    , "  Target Snap ID:    " <> srrTargetSnapId r
    , "  Restored Files:    " <> T.pack (show (length (srrRestoredFiles r)))
    , "  Removed Files:     " <> T.pack (show (length (srrRemovedFiles r)))
    , "  Unchanged Skipped: " <> T.pack (show (srrUnchangedSkip r))
    , "  Latency:           " <> T.pack (formatDurationMs (srrElapsedMs r))
    ]
    ++ (if null (srrRestoredFiles r)
          then []
          else "--------------------------------------------------------------------------------"
                 : ["  Restored:  " <> T.pack p | p <- srrRestoredFiles r])
    ++ (if null (srrRemovedFiles r)
          then []
          else "--------------------------------------------------------------------------------"
                 : ["  Removed:   " <> T.pack p | p <- srrRemovedFiles r])
    ++ [ "================================================================================" ]

formatSnapRewindJson :: SnapRewindReport -> LBS.ByteString
formatSnapRewindJson = AesonPretty.encodePretty

formatSnapLog :: Maybe Text -> [LedgerEntry] -> Text
formatSnapLog mHead entries =
  T.unlines $
    [ "================================================================================"
    , "  CANONTRA SNAP LEDGER (" <> T.toUpper snapStability <> ")"
    , "================================================================================"
    , "  Active HEAD:       " <> maybe "(none)" id mHead
    , "  Entries Shown:     " <> T.pack (show (length entries))
    , "--------------------------------------------------------------------------------"
    ]
    ++
    [ "  " <> (if Just (leSnapId e) == mHead then "* " else "  ")
        <> leSnapId e
        <> "  [" <> classificationText (leClassification e) <> "]"
        <> "  files=" <> T.pack (show (leFileCount e))
        <> "  changed=" <> T.pack (show (leChangedCount e))
        <> maybe "" (\l -> "  label=" <> l) (leLabel e)
        <> maybe "" (\a -> "  agent=" <> a) (leAgent e)
    | e <- entries
    ]
    ++ [ "================================================================================" ]

formatSnapLogJson :: Maybe Text -> [LedgerEntry] -> LBS.ByteString
formatSnapLogJson mHead entries =
  AesonPretty.encodePretty $ object
    [ "schema_version" .= snapSchemaVersion
    , "stability"      .= snapStability
    , "head"           .= mHead
    , "entries"        .= entries
    ]

formatSnapGC :: SnapGCReport -> Text
formatSnapGC r =
  T.unlines
    [ "================================================================================"
    , "  CANONTRA SNAP GARBAGE COLLECTION"
    , "================================================================================"
    , "  Retained Snaps:    " <> T.pack (show (gcrRetainedSnaps r))
    , "  Pruned Snaps:      " <> T.pack (show (gcrPrunedSnaps r))
    , "  Live Blobs:        " <> T.pack (show (gcrLiveBlobs r))
    , "  Removed Blobs:     " <> T.pack (show (gcrRemovedBlobs r))
    , "  Reclaimed Bytes:   " <> T.pack (show (gcrReclaimedBytes r))
    , "================================================================================"
    ]

formatSnapGCJson :: SnapGCReport -> LBS.ByteString
formatSnapGCJson = AesonPretty.encodePretty