canontra-0.4.0.0: src/Canontra/Harness/Guard.hs
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StrictData #-}
{- |
Module : Canontra.Harness.Guard
Description : Deterministic semantic policy gate (@canontra snap guard@) for AI harnesses.
Evaluates the live workspace against a baseline snapshot (@snap_0@, @HEAD@, or any
@snap_id@) and rejects mutations touching forbidden fingerprint tiers (e.g. @F2,F3,F_T@
during a refactor-only agent turn). Emits machine-readable JSON diagnostics and returns
POSIX exit code 0 (pass) or 1 (violation).
-}
module Canontra.Harness.Guard
( GuardTier (..)
, guardTierName
, parseGuardTiers
, matchesGlob
, GuardViolation (..)
, SnapGuardReport (..)
, snapGuard
, formatSnapGuard
, formatSnapGuardJson
) where
import Control.DeepSeq (NFData)
import Data.Aeson (ToJSON (..), object, (.=))
import qualified Data.Aeson.Encode.Pretty as AesonPretty
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Clock (getMonotonicTimeNSec)
import GHC.Generics (Generic)
import Canontra.Harness.Store
( SnapFileDelta (..)
, SnapManifest (..)
, readSnapManifest
)
import Canontra.Harness.SubVersion
( computeFileDeltas
, scanWorkspaceRecords
)
import Canontra.Normalize.Rules (snapSchemaVersion, snapStability)
import Canontra.Repository.Repository (normalizePathPosix)
-- | Fingerprint tiers enforceable by @canontra snap guard --forbid@.
data GuardTier
= TierF0
| TierF1
| TierF2
| TierF3
| TierFCG
| TierFCF
| TierFDF
| TierFT
| TierF4
deriving stock (Eq, Ord, Show, Generic)
deriving anyclass (NFData)
-- | Canonical tier identifier string matching 'diffFileBundles'.
guardTierName :: GuardTier -> Text
guardTierName = \case
TierF0 -> "F0"
TierF1 -> "F1"
TierF2 -> "F2"
TierF3 -> "F3"
TierFCG -> "F_CG"
TierFCF -> "F_CF"
TierFDF -> "F_DF"
TierFT -> "F_T"
TierF4 -> "F4"
instance ToJSON GuardTier where
toJSON = toJSON . guardTierName
-- | Parse comma-separated tier names (e.g. @"F2,F3,F_T"@).
parseGuardTiers :: Text -> Either String [GuardTier]
parseGuardTiers raw =
let parts = filter (not . T.null) (map T.strip (T.splitOn "," raw))
in if null parts
then Left "Empty --forbid tier list (expected e.g. F2,F3,F_T)"
else mapM parseOne parts
where
parseOne txt = case T.toUpper txt of
"F0" -> Right TierF0
"F1" -> Right TierF1
"F2" -> Right TierF2
"F3" -> Right TierF3
"F_CG" -> Right TierFCG
"FCG" -> Right TierFCG
"F_CF" -> Right TierFCF
"FCF" -> Right TierFCF
"F_DF" -> Right TierFDF
"FDF" -> Right TierFDF
"F_T" -> Right TierFT
"FT" -> Right TierFT
"F4" -> Right TierF4
_ -> Left ("Unknown guard tier '" ++ T.unpack txt
++ "' (valid: F0, F1, F2, F3, F_CG, F_CF, F_DF, F_T, F4)")
-- | Pure POSIX glob matcher supporting @**@ (multi-segment), @*@ (single segment), and @?@.
matchesGlob :: Text -> Text -> Bool
matchesGlob rawPat rawPath =
let patSegs = filter (not . T.null) (T.splitOn "/" (normSlashes rawPat))
pathSegs = filter (not . T.null) (T.splitOn "/" (normSlashes rawPath))
in matchSegs patSegs pathSegs
where
normSlashes = T.pack . normalizePathPosix . T.unpack
matchSegs [] [] = True
matchSegs ("**" : ps) xs =
matchSegs ps xs || case xs of
(_ : xr) -> matchSegs ("**" : ps) xr
[] -> False
matchSegs (p : ps) (x : xs) =
matchWord (T.unpack p) (T.unpack x) && matchSegs ps xs
matchSegs _ _ = False
matchWord [] [] = True
matchWord ('*' : ps) xs =
matchWord ps xs || case xs of
(_ : xr) -> matchWord ('*' : ps) xr
[] -> False
matchWord ('?' : ps) (_ : xs) = matchWord ps xs
matchWord (p : ps) (x : xs) = p == x && matchWord ps xs
matchWord _ _ = False
-- | Single file policy violation under @snap guard@.
data GuardViolation = GuardViolation
{ gvPath :: !FilePath
, gvStatus :: !Text
, gvSeverity :: !Text
, gvViolatedTiers :: ![Text]
, gvMutatedTiers :: ![Text]
} deriving stock (Eq, Show, Generic)
deriving anyclass (NFData)
instance ToJSON GuardViolation where
toJSON v = object
[ "path" .= gvPath v
, "status" .= gvStatus v
, "severity" .= gvSeverity v
, "violated_tiers" .= gvViolatedTiers v
, "mutated_tiers" .= gvMutatedTiers v
]
-- | Full evaluation report returned by @canontra snap guard@.
data SnapGuardReport = SnapGuardReport
{ sgrSchemaVersion :: !Text
, sgrStability :: !Text
, sgrAgainstSnapId :: !Text
, sgrForbiddenTiers :: ![Text]
, sgrAllowPaths :: ![Text]
, sgrPassed :: !Bool
, sgrViolations :: ![GuardViolation]
, sgrAllowedSkipped :: ![FilePath]
, sgrElapsedMs :: !Double
} deriving stock (Eq, Show, Generic)
deriving anyclass (NFData)
instance ToJSON SnapGuardReport where
toJSON r = object
[ "schema_version" .= sgrSchemaVersion r
, "stability" .= sgrStability r
, "against_snap_id" .= sgrAgainstSnapId r
, "forbidden_tiers" .= sgrForbiddenTiers r
, "allow_paths" .= sgrAllowPaths r
, "passed" .= sgrPassed r
, "violations" .= sgrViolations r
, "allowed_skipped" .= sgrAllowedSkipped r
, "elapsed_ms" .= sgrElapsedMs r
]
-- | Evaluate live workspace mutations against a baseline snapshot and forbidden tiers.
snapGuard
:: FilePath
-> Text
-> [GuardTier]
-> [Text]
-> IO (Either String SnapGuardReport)
snapGuard repoDir againstRef forbiddenTiers allowGlobs = do
t0 <- getMonotonicTimeNSec
eBase <- readSnapManifest repoDir againstRef
case eBase of
Left err -> pure (Left err)
Right baseMan -> do
eScan <- scanWorkspaceRecords repoDir
case eScan of
Left err -> pure (Left err)
Right (_, liveRecords) -> do
let deltas = computeFileDeltas (smFiles baseMan) liveRecords
forbiddenNames = map guardTierName forbiddenTiers
forbiddenSet = Set.fromList forbiddenNames
(allowedList, checkedDeltas) = foldr partitionAllow ([], []) deltas
violations =
[ GuardViolation
(sfdPath d)
(sfdStatus d)
(sfdSeverity d)
hits
(sfdMutatedTiers d)
| d <- checkedDeltas
, let hits = filter (`Set.member` forbiddenSet) (sfdMutatedTiers d)
, not (null hits)
]
t1 <- getMonotonicTimeNSec
let !elapsed = fromIntegral (toInteger t1 - toInteger t0) / 1000000.0
pure $ Right SnapGuardReport
{ sgrSchemaVersion = snapSchemaVersion
, sgrStability = snapStability
, sgrAgainstSnapId = smSnapId baseMan
, sgrForbiddenTiers = forbiddenNames
, sgrAllowPaths = allowGlobs
, sgrPassed = null violations
, sgrViolations = violations
, sgrAllowedSkipped = allowedList
, sgrElapsedMs = elapsed
}
where
partitionAllow d (al, chk)
| any (\g -> matchesGlob g (T.pack (sfdPath d))) allowGlobs =
(sfdPath d : al, chk)
| otherwise =
(al, d : chk)
formatSnapGuard :: SnapGuardReport -> Text
formatSnapGuard r =
T.unlines $
[ "================================================================================"
, " CANONTRA SNAP GUARD (" <> T.toUpper snapStability <> ")"
, "================================================================================"
, " Against Snap: " <> sgrAgainstSnapId r
, " Forbidden Tiers: " <> T.intercalate "," (sgrForbiddenTiers r)
, " Status: " <> if sgrPassed r then "PASS (0 policy violations)" else "FAIL (" <> T.pack (show (length (sgrViolations r))) <> " violation(s))"
, " Latency: " <> T.pack (show (round1 (sgrElapsedMs r))) <> " ms"
]
++ (if null (sgrViolations r)
then []
else
[ "--------------------------------------------------------------------------------"
, " Policy Violations:"
] ++
[ " [VIOLATION] " <> T.pack (gvPath v)
<> " (" <> gvStatus v <> ", forbidden: " <> T.intercalate "," (gvViolatedTiers v) <> ")"
| v <- sgrViolations r
])
++ [ "================================================================================" ]
where
round1 :: Double -> Double
round1 x = fromIntegral (round (x * 100.0) :: Int) / 100.0
formatSnapGuardJson :: SnapGuardReport -> LBS.ByteString
formatSnapGuardJson = AesonPretty.encodePretty