okf-core-0.14.0.0: src/Okf/Bundle.hs
-- | Bundle-level discovery for OKF concept documents.
module Okf.Bundle
( BundleError (..),
BundleInventory,
UntypedMarkdown (..),
walkBundleDocuments,
bundleInventoryDirectories,
bundleInventoryFiles,
readBundleDocument,
tryBundleIo,
Concept,
LogFile (..),
bundleInventoryMember,
bundleInventoryContainsPath,
bundleInventoryOfConcepts,
walkBundleInventory,
conceptFromDocument,
conceptAttester,
conceptComputation,
conceptComputationSources,
conceptDescription,
conceptDocument,
conceptExecutor,
conceptGenerated,
conceptIdOf,
conceptParameters,
conceptPathFields,
conceptResource,
conceptRuntime,
conceptSourcePath,
conceptSources,
conceptSupersededBy,
conceptStaleAfter,
conceptStatus,
conceptTags,
conceptUsageWindow,
conceptTitle,
conceptType,
conceptVerified,
findConcept,
findConceptsByDocumentId,
isReservedMarkdownFile,
serializeConcept,
walkBundle,
walkLogs,
writeBundle,
)
where
import Control.Exception (IOException, try)
import Data.Aeson.KeyMap qualified as KeyMap
import Data.Either (partitionEithers)
import Data.Foldable (for_)
import Data.List qualified as List
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Text qualified as Text
import Data.Text.IO qualified as Text.IO
import Okf.BundlePath
import Okf.ConceptId
import Okf.Document
import Okf.Log
import Okf.Prelude
import System.Directory (createDirectoryIfMissing)
import System.FilePath qualified as FilePath
import System.IO.Error (ioeGetErrorString)
-- | A parsed concept document discovered in a bundle.
data Concept = Concept
{ id :: !ConceptId,
sourcePath :: !FilePath,
document :: !OKFDocument,
type_ :: !Text,
title :: !(Maybe Text),
description :: !(Maybe Text),
resource :: !(Maybe Text),
tags :: ![Text],
generated :: !(Maybe Generated),
verified :: ![Verification],
status :: !Status,
staleAfter :: !(Maybe Text),
sources :: ![Source],
usageWindow :: !(Maybe UsageWindow),
runtime :: !(Maybe Text),
parameters :: ![Parameter],
computation :: !(Maybe Text),
executor :: !(Maybe Executor),
attester :: !(Maybe Attester),
computationSources :: ![ComputationSource]
}
deriving stock (Generic, Eq, Show)
-- | Filesystem or parser failures while walking a bundle.
data BundleError
= InvalidConceptPath FilePath ConceptIdError
| InvalidConceptDocument FilePath DocumentParseError
| InvalidReservedFile FilePath Text
| BundleIoError FilePath Text
deriving stock (Generic, Eq, Show)
-- | Every regular file in a bundle, as bundle-relative paths, whether or not okf
-- can parse it. Concepts are the @.md@ subset; a @references\/@ script, a CSV, or
-- an image is here and nowhere else.
--
-- This exists so that a path-valued frontmatter field can be resolved without
-- giving validation a filesystem handle. Validation is offline by design
-- (@docs\/adr\/5-compile-profile-rules-before-validation.md@): it receives parsed
-- values and decides. Reading the inventory once during the walk, where okf is
-- already doing IO, keeps it that way.
data BundleInventory = BundleInventory !(Set FilePath) !(Set FilePath)
deriving stock (Generic, Eq, Show)
-- | A parsed @log.md@ reserved file discovered in a bundle.
data LogFile = LogFile
{ logSourcePath :: !FilePath,
logContent :: !Log
}
deriving stock (Generic, Eq, Show)
-- | A Markdown document that has no nonempty textual type.
data UntypedMarkdown = UntypedMarkdown
{ untypedSourcePath :: !FilePath,
untypedDocument :: !OKFDocument
}
deriving stock (Generic, Eq, Show)
-- | Discover and parse every non-reserved Markdown concept in a bundle.
walkBundle :: FilePath -> IO (Either BundleError [Concept])
walkBundle root = fmap fst <$> walkBundleDocuments root
-- | Keep untyped Markdown available to callers that validate house records.
walkBundleDocuments :: FilePath -> IO (Either BundleError ([Concept], [UntypedMarkdown]))
walkBundleDocuments root = do
discovered <- walkBundleInventory root
case discovered of
Left bundleError -> pure (Left bundleError)
Right inventory -> do
let candidates =
[ path
| path <- bundleInventoryFiles inventory,
FilePath.takeExtension path == ".md",
not (isReservedMarkdownFile path)
]
results <- traverse readCandidate candidates
pure $ do
classified <- sequenceA results
let (concepts, untyped) = partitionEithers classified
pure (List.sortOn (renderConceptId . conceptIdOf) concepts, untyped)
where
readCandidate path = do
parsed <- readBundleDocument root path
pure $ do
document <- parsed
if hasConceptType (frontmatter document)
then do
conceptId <- first (InvalidConceptPath path) (conceptIdFromFilePath path)
pure (Left (conceptAt conceptId path document))
else pure (Right (UntypedMarkdown path document))
-- | Discover and parse every @log.md@ reserved file in a bundle.
walkLogs :: FilePath -> IO (Either BundleError [LogFile])
walkLogs root = do
discovered <- walkBundleInventory root
case discovered of
Left bundleError -> pure (Left bundleError)
Right inventory -> do
let paths = filter ((== "log.md") . FilePath.takeFileName) (bundleInventoryFiles inventory)
sequenceA <$> traverse (readLog root) paths
-- | Record every visible regular file under the root.
walkBundleInventory :: FilePath -> IO (Either BundleError BundleInventory)
walkBundleInventory root =
fmap inventory <$> bundleEntries root
where
inventory entries =
BundleInventory
(Set.fromList [path | BundleFile path <- entries])
(Set.fromList ("." : [path | BundleDirectory path <- entries]))
bundleInventoryFiles :: BundleInventory -> [FilePath]
bundleInventoryFiles (BundleInventory paths _) = Set.toAscList paths
-- | Include the root once, plus all visible real directories.
bundleInventoryDirectories :: BundleInventory -> [FilePath]
bundleInventoryDirectories (BundleInventory _ dirs) =
"" : Set.toAscList (Set.delete "." dirs)
bundleEntries :: FilePath -> IO (Either BundleError [BundleEntry])
bundleEntries root = walk ""
where
walk directory = do
listed <- tryBundleIo (if null directory then root else directory) (listBundleDirectory root directory)
case listed of
Left bundleError -> pure (Left bundleError)
Right entries -> do
nested <- traverse descend entries
pure (concat <$> sequenceA nested)
descend entry@(BundleDirectory path) = fmap (entry :) <$> walk path
descend entry = pure (Right [entry])
-- | Whether the bundle contains a file at the given bundle-relative path. The
-- path is normalised the same way the inventory's entries are, so a caller may
-- pass 'Okf.Path.collapseBundlePath' output directly.
bundleInventoryMember :: FilePath -> BundleInventory -> Bool
bundleInventoryMember path (BundleInventory paths _) =
Set.member (FilePath.normalise path) paths
-- | Path fields and Markdown may refer to an indexed directory as well as
-- a file. Use 'bundleInventoryMember' when the operation requires a file.
bundleInventoryContainsPath :: FilePath -> BundleInventory -> Bool
bundleInventoryContainsPath path (BundleInventory files dirs) =
Set.member normalized files || Set.member normalized dirs
where
normalized = FilePath.normalise path
-- | The inventory an in-memory bundle can honestly report: the concepts' own
-- source paths and nothing else.
--
-- For producers that assemble concepts without a directory to walk. Such a
-- bundle resolves concept-to-concept paths correctly and simply cannot know
-- about a non-Markdown file, because there is no filesystem holding one.
bundleInventoryOfConcepts :: [Concept] -> BundleInventory
bundleInventoryOfConcepts concepts =
BundleInventory (Set.fromList paths) (Set.fromList ("." : concatMap parents paths))
where
paths = map (FilePath.normalise . conceptSourcePath) concepts
parents path =
let parent = FilePath.takeDirectory path
in if parent == "." || parent == path then [] else parent : parents parent
-- | Find a concept by identifier in an already walked bundle.
findConcept :: ConceptId -> [Concept] -> Maybe Concept
findConcept conceptId =
List.find (\concept -> conceptIdOf concept == conceptId)
-- | Find concepts whose frontmatter carries the given document handle. When a
-- field is supplied, only that key is examined; otherwise every frontmatter
-- value is searched. All matches are returned so callers can report ambiguity.
findConceptsByDocumentId :: Maybe Text -> Text -> [Concept] -> [Concept]
findConceptsByDocumentId fieldFilter handle =
filter conceptMatches
where
conceptMatches concept =
case fieldFilter of
Just fieldName ->
valueMatches (frontmatterLookup fieldName (documentFrontmatter concept))
Nothing ->
any (valueMatches . Just) (KeyMap.elems (fields (documentFrontmatter concept)))
valueMatches (Just (String value)) = Text.strip value == handle
valueMatches _ = False
documentFrontmatter concept = frontmatter (conceptDocument concept)
-- | Extract a concept identifier without colliding with Prelude's `id`.
conceptIdOf :: Concept -> ConceptId
conceptIdOf Concept {id = conceptId} = conceptId
-- | Bundle-relative path the concept was read from or would be written to.
conceptSourcePath :: Concept -> FilePath
conceptSourcePath Concept {sourcePath} = sourcePath
-- | Parsed Markdown document backing the concept.
conceptDocument :: Concept -> OKFDocument
conceptDocument Concept {document} = document
-- | Required @type@ frontmatter field projected as text, or empty when invalid.
conceptType :: Concept -> Text
conceptType Concept {type_} = type_
conceptTitle :: Concept -> Maybe Text
conceptTitle Concept {title} = title
conceptDescription :: Concept -> Maybe Text
conceptDescription Concept {description} = description
conceptResource :: Concept -> Maybe Text
conceptResource Concept {resource} = resource
conceptTags :: Concept -> [Text]
conceptTags Concept {tags} = tags
-- | The OKF v0.2 @generated@ family projected from frontmatter, or 'Nothing'
-- when the concept carries none (or carries one without the @by@ actor that
-- specification §5.2 requires within it).
conceptGenerated :: Concept -> Maybe Generated
conceptGenerated Concept {generated} = generated
-- | The OKF v0.2 @verified@ family projected from frontmatter, empty when the
-- concept carries none. A bare @{ by, at }@ mapping projects as one element,
-- per the specification §5.2 MUST.
--
-- Note what is /not/ here: the trust tier §5.3 derives from this list is a
-- function of it, not a field beside it. See
-- @docs\/adr\/8-derived-not-stored-trust-and-credibility.md@ and use
-- @Okf.Trust.trustTier . conceptVerified@.
conceptVerified :: Concept -> [Verification]
conceptVerified Concept {verified} = verified
-- | The OKF v0.2 @status@ lifecycle field, 'Stable' when the concept carries
-- none (specification §5.4).
conceptStatus :: Concept -> Status
conceptStatus Concept {status} = status
-- | The replacement reference as written, irrespective of lifecycle state.
conceptSupersededBy :: Concept -> Maybe Text
conceptSupersededBy = readSupersededBy . frontmatter . conceptDocument
-- | The OKF v0.2 @stale_after@ date read verbatim (specification §5.5).
-- Interpreting it against a calendar day is 'Okf.Trust.staleness''s job.
conceptStaleAfter :: Concept -> Maybe Text
conceptStaleAfter Concept {staleAfter} = staleAfter
-- | The OKF v0.2 @sources@ provenance entries projected from frontmatter,
-- empty when the concept carries none (specification §5.1). Entries lacking the
-- required @resource@ are absent here; 'Okf.Validation.validateDocument'
-- reports them.
conceptSources :: Concept -> [Source]
conceptSources Concept {sources} = sources
-- | The document-scope @usage_window@ that frames every entry's @usage_count@
-- (specification §5.1). Resolve a given entry's effective window with
-- @Okf.Document.effectiveUsageWindow (conceptUsageWindow concept)@, which
-- honours a per-entry override.
conceptUsageWindow :: Concept -> Maybe UsageWindow
conceptUsageWindow Concept {usageWindow} = usageWindow
-- | The format-defined fields that can contribute a path or URI relationship.
-- Some source resources are scope descriptions and will resolve to no file.
conceptPathFields :: Concept -> [(Text, Text)]
conceptPathFields concept =
present "resource" (conceptResource concept)
<> [("sources[].resource", sourceResource source) | source <- conceptSources concept]
<> present "computation" (conceptComputation concept)
<> present "executor.resource" (executorResource =<< conceptExecutor concept)
<> present "attester.resource" (attesterResource =<< conceptAttester concept)
<> present "superseded_by" (conceptSupersededBy concept)
where
present name = maybe [] (\target -> [(name, target)])
-- | The @runtime@ that says how an attested computation is run, and so what its
-- @parameters@ mean (specification §10.2).
--
-- Present on any concept that declares it, not only on one whose @type@ is
-- @Attested Computation@: a projection restates what frontmatter says and
-- nothing more. Only 'Okf.Validation.validateDocument' knows that the field is
-- REQUIRED for that one type.
conceptRuntime :: Concept -> Maybe Text
conceptRuntime Concept {runtime} = runtime
-- | The typed, named holes an agent may fill (specification §10.2), empty when
-- the concept declares none. An entry with no @name@ is absent here.
conceptParameters :: Concept -> [Parameter]
conceptParameters Concept {parameters} = parameters
-- | The §6.2 path to a file holding the computation, when the concept names one
-- instead of carrying an inline body fence (specification §10.2, §10.3).
--
-- Verbatim, and not resolved against the bundle. Resolving a path-valued
-- frontmatter field is 'Okf.Validation.validateBundle''s job, which has the
-- 'BundleInventory' this projection does not.
conceptComputation :: Concept -> Maybe Text
conceptComputation Concept {computation} = computation
-- | How the computation is run and what evidence a run must return
-- (specification §10.2). okf never runs it; §10.5 places the run and its receipt
-- outside the bundle.
conceptExecutor :: Concept -> Maybe Executor
conceptExecutor Concept {executor} = executor
-- | The deterministic, no-LLM check that inspects a receipt (specification
-- §10.2). okf never runs it and never computes a verdict.
conceptAttester :: Concept -> Maybe Attester
conceptAttester Concept {attester} = attester
-- | Every computation the concept offers (specification §10.3), file before
-- inline. Empty when it offers none.
--
-- Unlike 'conceptComputation', which restates the frontmatter key verbatim, this
-- also sees the body. §10.3's rule that exactly one of the two forms must be
-- present is 'Okf.Validation.validateDocument''s to report.
conceptComputationSources :: Concept -> [ComputationSource]
conceptComputationSources Concept {computationSources} = computationSources
-- | Reserved Markdown filenames are not normal concept documents.
isReservedMarkdownFile :: FilePath -> Bool
isReservedMarkdownFile path =
FilePath.takeFileName path `List.elem` ["index.md", "log.md"]
-- | Write the supplied concepts after checking all destination paths.
writeBundle :: FilePath -> [Concept] -> IO ()
writeBundle root concepts = do
targets <- for concepts $ \concept -> do
let relative = conceptIdToFilePath (conceptIdOf concept)
absolute <- requireBundlePath root relative
pure (absolute, serializeConcept concept)
for_ targets $ \(absolute, content) -> do
createDirectoryIfMissing True (FilePath.takeDirectory absolute)
Text.IO.writeFile absolute content
-- | Serialize a single concept's document to a Markdown string.
serializeConcept :: Concept -> Text
serializeConcept = serializeDocument . document
readBundleDocument :: FilePath -> FilePath -> IO (Either BundleError OKFDocument)
readBundleDocument root relativePath = do
loaded <- tryBundleIo relativePath (requireBundlePath root relativePath >>= Text.IO.readFile)
pure (loaded >>= first (InvalidConceptDocument relativePath) . parseDocument)
readLog :: FilePath -> FilePath -> IO (Either BundleError LogFile)
readLog root relativePath = do
loaded <- tryBundleIo relativePath (requireBundlePath root relativePath >>= Text.IO.readFile)
pure $ do
content <- loaded
if hasFrontmatterFence content
then Left (InvalidReservedFile relativePath "log.md must not have YAML frontmatter")
else pure (LogFile {logSourcePath = relativePath, logContent = parseLog content})
tryBundleIo :: FilePath -> IO value -> IO (Either BundleError value)
tryBundleIo path action = do
result <- try action
pure
( case result of
Right value -> Right value
Left (exception :: IOException) -> Left (BundleIoError path (Text.pack (ioeGetErrorString exception)))
)
-- | Build a 'Concept' from its identity and document. The typed projection
-- fields (@type_@, @title@, @description@, @resource@, @tags@, @generated@,
-- @verified@, @status@, @staleAfter@, @sources@, @usageWindow@, @runtime@,
-- @parameters@, @computation@, @executor@, @attester@) are derived
-- from the document's frontmatter, so they can never disagree with it.
-- A projection may only restate what frontmatter says; it may never store a
-- derivation frontmatter does not carry.
--
-- @computationSources@ is the one field derived from the whole document rather
-- than from frontmatter alone, because specification §10.3 makes the
-- @computation@ key and the body's @# Computation@ section alternatives to each
-- other. Restating what the /document/ says, both halves together, is still
-- restating rather than deriving.
--
-- The source
-- path is derived from the concept ID. Use this when assembling concepts in
-- memory (for 'writeBundle' or 'Okf.Validation.validateBundle').
conceptFromDocument :: ConceptId -> OKFDocument -> Concept
conceptFromDocument conceptId =
conceptAt conceptId (conceptIdToFilePath conceptId)
-- | Build a 'Concept' with an explicit on-disk source path (used by the reader).
conceptAt :: ConceptId -> FilePath -> OKFDocument -> Concept
conceptAt conceptId relativePath document =
Concept
{ id = conceptId,
sourcePath = relativePath,
document,
type_ = textField "type" (frontmatter document),
title = optionalTextField "title" (frontmatter document),
description = optionalTextField "description" (frontmatter document),
resource = optionalTextField "resource" (frontmatter document),
tags = tagsField (frontmatter document),
generated = readGenerated (frontmatter document),
verified = readVerified (frontmatter document),
status = readStatus (frontmatter document),
staleAfter = readStaleAfter (frontmatter document),
sources = readSources (frontmatter document),
usageWindow = readUsageWindow (frontmatter document),
runtime = readRuntime (frontmatter document),
parameters = readParameters (frontmatter document),
computation = readComputation (frontmatter document),
executor = readExecutor (frontmatter document),
attester = readAttester (frontmatter document),
computationSources = readComputationSources document
}
textField :: Text -> Frontmatter -> Text
textField key frontmatter =
fromMaybe "" (optionalTextField key frontmatter)
optionalTextField :: Text -> Frontmatter -> Maybe Text
optionalTextField key frontmatter =
case frontmatterLookup key frontmatter of
Just (String value) -> Just value
_ -> Nothing
tagsField :: Frontmatter -> [Text]
tagsField fm =
[ value
| String value <- listFieldValues "tags" fm,
not (Text.null value)
]