packages feed

okf-core 0.9.0.0 → 0.13.0.0

raw patch · 115 files changed

Files

CHANGELOG.md view
@@ -7,6 +7,104 @@  ## [Unreleased] +## [0.13.0.0] - 2026-11-08++### Added++- `Okf.Log.insertLogEntry` inserts an entry into original Markdown while+  preserving existing content and formatting, refusing unsafe insertion.+- `Okf.Log.renderLogDiff` renders an exact unified diff against source Markdown+  or a new file, including deletions and line-ending changes.++## [0.12.0.1] - 2026-10-28++### Fixed++- Render nonempty indexes with one final newline and empty indexes without a+  blank line, preserving root version frontmatter.+- Remove trailing spaces and tabs from bootstrap descriptor comments, including+  multiline source annotations, without changing Dhall expressions.++## [0.12.0.0] - 2026-10-28++### Added++- `Okf.Profile.Sweep`: enumerate and apply relaxations of an authored+  `ProfileSpec`, load a sweep suite (acceptance bundles and `expected.json`+  cases in file order), check its baseline, and observe each relaxation's+  witnesses with the okf-profiles catalog's legacy predicate. `sweepProfile`+  classifies each relaxation by evidence and proof: `behaviourKey` proves+  inertness with documented erasures, composite policy units and+  `admitValue` relaxations cover what one relaxation alone cannot show, and+  `parseExceptions` reads a per-suite exception manifest.++## [0.11.0.0] - 2026-10-28++### Added++- Bounded `ValueSelector` declarations, grouped presence, timestamp ordering,+  text membership, combined uniqueness, and `FiniteDecimal` validation. Effective+  root and nested constraints have read-only inspection APIs; generated profile+  documentation renders them. Frozen compatibility decoders preserve complete+  historical descriptor generations in file and registry workflows.+- Opt-in `NestedRules.allowUnknownFields` closure for list records and object+  values, defaulting to open. Names merge by union and policies with AND across+  scopes; diagnostics use indexed/member paths in both validation modes. Raw+  inspection exposes declared booleans and generated documentation shows+  effective open/closed/none policies. Older descriptors retain open records.++### Changed++- Requires GHC >=9.12 (base >=4.21). Profile/configuration exception handling+  preserves asynchronous cancellation.+- **Breaking (library/schema):** `FrontmatterRules` gains four constraint lists;+  `NestedRules` gains two constraint lists and `allowUnknownFields`; `FieldFormat`+  gains `FiniteDecimal`. Use record completion for new defaulted fields or retain+  a frozen older schema import for existing descriptors.+- **Breaking (library):** New error/violation constructors are+  `InvalidConceptConstraint`, `ConstraintPresenceMissing`,+  `ConstraintAlternativeMissing`, `TimestampOrderViolation`, `TextOperandMismatch`,+  `MembershipValueMissing`, `DuplicateSelectedValue`, and+  `NestedFieldNotInProfile ConceptId FieldPath`. Exhaustive consumers must handle+  them, including `mori://shinzui/mori/packages/mori-cli`.+- `defaultRegistryReference` now pins `mori://shinzui/okf-profiles` v0.25.0+  (from v0.19.0), with thirty profiles verified by the offline catalogue fixture.+  New exports cover transitions, runbooks, product discovery, designs, friction+  logs, campaigns, audiences, claim checks, strategy, launches, and messaging.++## [0.10.0.0] - 2026-10-06++### Added++- `Okf.Profile.Bootstrap` renders adoption descriptors with Dhall path/label escaping, remote import freezing, local relative imports, and maximum-version selection.++- `Okf.Query` gains flexible concept conditions: `WhereCondition`,+  `ConceptPredicate`, `WhereParseError`, `parseWhereCondition`,+  `renderWhereCondition`, `renderConceptPredicate`, `renderWhereParseError`,+  `matchesPredicate`, `filterConceptsWhere`, and+  `checkPredicateAgainstProfile`. Conditions add `!=`, `in`, `not in`, and+  parenthesized `and`/`or`/`not` expressions with `has(KEY)` and+  `missing(KEY)`. Negative value predicates require a comparable scalar and+  reject a list when any element is excluded; `not` negates its whole operand.+  Profile checks cover every operand. Existing `ConceptFilter` APIs and their+  semantics are unchanged.++- `Okf.Query` gains concept ordering: `SortDirection`, `SortKey`,+  `SortKeyParseError`, `parseSortKey`, `renderSortKey`,+  `renderSortKeyParseError`, `compareNatural`, and `sortConcepts`. Text+  compares in natural order (`IR-2` before `IR-10`), numbers numerically and+  before text, concepts without a comparable value last in both directions,+  lists by their smallest or largest element, and ties in input order.+  `okf-core` now depends on `scientific` directly.++### Changed++- `defaultRegistryReference` now pins `mori://shinzui/okf-profiles` v0.19.0+  (from v0.14.0); the offline catalogue conformance fixture decodes all+  seventeen published profiles, adding `assurance.verificationEvidence`,+  `coordination.patternApplications`, `documentation.specifications`, and+  `documentation.terminology`.+ ## [0.9.0.0] - 2026-09-13  ### Added
dhall/FieldFormat.dhall view
@@ -15,5 +15,6 @@ | HumanActor | Integer | NonNegativeInteger+| FiniteDecimal | Boolean >
dhall/FrontmatterRules.dhall view
@@ -19,4 +19,8 @@ in  { required : List FieldRule     , recommended : List FieldRule     , optional : List FieldRule+    , presenceConstraints : List ./PresenceConstraint.dhall+    , timestampOrderConstraints : List ./TimestampOrderConstraint.dhall+    , membershipConstraints : List ./MembershipConstraint.dhall+    , uniqueValuesConstraints : List ./UniqueValuesConstraint.dhall     }
+ dhall/MembershipConstraint.dhall view
@@ -0,0 +1,1 @@+{ source : ./ValueSelector.dhall, target : ./ValueSelector.dhall }
dhall/NestedRules.dhall view
@@ -5,9 +5,15 @@ -- always checked, `recommended` only under `--strict`, and an `optional` member -- is never reported when absent while its declared constraints still apply -- whenever it is present.+-- Set allowUnknownFields to False to reject every supplied undeclared member.+-- All three declaration lists contribute names even when a presence condition+-- is false. Matching profile/type policies combine with AND. let NestedFieldRule = ./NestedFieldRule.dhall -in  { required : List NestedFieldRule+in  { allowUnknownFields : Bool+    , required : List NestedFieldRule     , recommended : List NestedFieldRule     , optional : List NestedFieldRule+    , presenceConstraints : List ./PresenceConstraint.dhall+    , timestampOrderConstraints : List ./TimestampOrderConstraint.dhall     }
+ dhall/PresenceConstraint.dhall view
@@ -0,0 +1,5 @@+{ when : Optional ./FieldCondition.dhall+, whenAnyPresent : List ./ValueSelector.dhall+, requireAll : List ./ValueSelector.dhall+, requireAny : List ./ValueSelector.dhall+}
+ dhall/TimestampOrderConstraint.dhall view
@@ -0,0 +1,1 @@+{ before : Text, after : Text }
+ dhall/UniqueValuesConstraint.dhall view
@@ -0,0 +1,1 @@+{ selectors : List ./ValueSelector.dhall }
+ dhall/ValueSelector.dhall view
@@ -0,0 +1,1 @@+{ field : Text, member : Optional Text }
dhall/defaults/FrontmatterRules.dhall view
@@ -8,5 +8,9 @@       { required = [] : List FieldRule       , recommended = [] : List FieldRule       , optional = [] : List FieldRule+      , presenceConstraints = [] : List ../PresenceConstraint.dhall+      , timestampOrderConstraints = [] : List ../TimestampOrderConstraint.dhall+      , membershipConstraints = [] : List ../MembershipConstraint.dhall+      , uniqueValuesConstraints = [] : List ../UniqueValuesConstraint.dhall       }     }
+ dhall/defaults/MembershipConstraint.dhall view
@@ -0,0 +1,5 @@+let Selector = ./ValueSelector.dhall++in  { Type = ../MembershipConstraint.dhall+    , default = { source = Selector::{=}, target = Selector::{=} }+    }
dhall/defaults/NestedRules.dhall view
@@ -6,8 +6,11 @@  in  { Type = NestedRulesType     , default =-      { required = [] : List NestedFieldRule+      { allowUnknownFields = True+      , required = [] : List NestedFieldRule       , recommended = [] : List NestedFieldRule       , optional = [] : List NestedFieldRule+      , presenceConstraints = [] : List ../PresenceConstraint.dhall+      , timestampOrderConstraints = [] : List ../TimestampOrderConstraint.dhall       }     }
+ dhall/defaults/PresenceConstraint.dhall view
@@ -0,0 +1,8 @@+{ Type = ../PresenceConstraint.dhall+, default =+  { when = None ../FieldCondition.dhall+  , whenAnyPresent = [] : List ../ValueSelector.dhall+  , requireAll = [] : List ../ValueSelector.dhall+  , requireAny = [] : List ../ValueSelector.dhall+  }+}
+ dhall/defaults/TimestampOrderConstraint.dhall view
@@ -0,0 +1,3 @@+{ Type = ../TimestampOrderConstraint.dhall+, default = { before = "", after = "" }+}
+ dhall/defaults/UniqueValuesConstraint.dhall view
@@ -0,0 +1,3 @@+{ Type = ../UniqueValuesConstraint.dhall+, default.selectors = [] : List ../ValueSelector.dhall+}
+ dhall/defaults/ValueSelector.dhall view
@@ -0,0 +1,1 @@+{ Type = ../ValueSelector.dhall, default = { field = "", member = None Text } }
dhall/package.dhall view
@@ -12,7 +12,8 @@ -- `defaults` holds the `{ Type, default }` record-completion modules; `mk` holds -- constructor functions for the types authors write repeatedly. Both protect a -- descriptor written from now on against future additive, defaulted schema--- fields; neither is a compatibility mechanism for descriptors that already+-- fields (including the open-by-default NestedRules.allowUnknownFields policy);+-- neither is a compatibility mechanism for descriptors that already -- exist (okf-core's legacy fallback decoder is what keeps those loading). { Profile = ./Profile.dhall , TypeRule = ./TypeRule.dhall@@ -25,8 +26,18 @@ , NestedFieldRule = ./NestedFieldRule.dhall , Cardinality = ./Cardinality.dhall , FieldFormat = ./FieldFormat.dhall+, ValueSelector = ./ValueSelector.dhall+, PresenceConstraint = ./PresenceConstraint.dhall+, TimestampOrderConstraint = ./TimestampOrderConstraint.dhall+, MembershipConstraint = ./MembershipConstraint.dhall+, UniqueValuesConstraint = ./UniqueValuesConstraint.dhall , defaults =-  { Profile = ./defaults/Profile.dhall+  { ValueSelector = ./defaults/ValueSelector.dhall+  , PresenceConstraint = ./defaults/PresenceConstraint.dhall+  , TimestampOrderConstraint = ./defaults/TimestampOrderConstraint.dhall+  , MembershipConstraint = ./defaults/MembershipConstraint.dhall+  , UniqueValuesConstraint = ./defaults/UniqueValuesConstraint.dhall+  , Profile = ./defaults/Profile.dhall   , TypeRule = ./defaults/TypeRule.dhall   , FrontmatterRules = ./defaults/FrontmatterRules.dhall   , FieldRule = ./defaults/FieldRule.dhall
okf-core.cabal view
@@ -1,6 +1,6 @@-cabal-version:      3.4-name:               okf-core-version:            0.9.0.0+cabal-version: 3.4+name: okf-core+version: 0.13.0.0 synopsis:   Read, validate, index, and traverse Open Knowledge Format bundles @@ -10,15 +10,14 @@   index and link graph, validates referential integrity, and writes bundles back   out with a round-trip guarantee. -category:           Data, Text-license:            BSD-3-Clause-license-file:       LICENSE-author:             Nadeem Bitar-maintainer:         nadeem@gmail.com-copyright:          (c) 2026 Nadeem Bitar-build-type:         Simple-extra-doc-files:    CHANGELOG.md-+category: Data, Text+license: BSD-3-Clause+license-file: LICENSE+author: Nadeem Bitar+maintainer: nadeem@gmail.com+copyright: (c) 2026 Nadeem Bitar+build-type: Simple+extra-doc-files: CHANGELOG.md -- The canonical profile schema, plus the fixtures okf-core-test reads. The -- fixture descriptors import the schema through ../../../dhall, so both trees -- must ship for `cabal test` to work from the sdist.@@ -28,6 +27,7 @@ extra-source-files:   dhall/**/*.dhall   test/fixtures/**/*.dhall+  test/fixtures/**/*.json   test/fixtures/**/*.md   test/fixtures/**/*.py   test/fixtures/**/*.sql@@ -35,12 +35,18 @@  common common-options   ghc-options:-    -Wall -Wcompat -Widentities -Wincomplete-uni-patterns-    -Wincomplete-record-updates -Wredundant-constraints-    -fhide-source-paths -Wmissing-export-lists -Wpartial-fields+    -Wall+    -Wcompat+    -Widentities+    -Wincomplete-uni-patterns+    -Wincomplete-record-updates+    -Wredundant-constraints+    -fhide-source-paths+    -Wmissing-export-lists+    -Wpartial-fields     -Wmissing-deriving-strategies -  default-language:   GHC2024+  default-language: GHC2024   default-extensions:     DeriveAnyClass     DuplicateRecordFields@@ -48,14 +54,15 @@     OverloadedStrings  library-  import:          common-options-  hs-source-dirs:  src+  import: common-options+  hs-source-dirs: src   exposed-modules:     Okf.Actor     Okf.Bundle     Okf.ConceptId     Okf.Discovery     Okf.Document+    Okf.Exception     Okf.Graph     Okf.Index     Okf.Log@@ -63,48 +70,51 @@     Okf.Path     Okf.Prelude     Okf.Profile+    Okf.Profile.Bootstrap     Okf.Profile.Discovery     Okf.Profile.Documentation     Okf.Profile.Registry+    Okf.Profile.Sweep     Okf.Query     Okf.Trust     Okf.Validation    build-depends:-    , aeson         >=2.2   && <2.4-    , attoparsec    >=0.14  && <0.15-    , base          >=4.20  && <5-    , bytestring    >=0.11  && <0.13-    , cmark-gfm     ^>=0.2-    , containers    >=0.6   && <0.8-    , dhall         >=1.41  && <1.43-    , directory     >=1.3   && <1.4-    , filepath      >=1.4   && <1.6-    , frontmatter   >=0.1   && <0.2-    , generic-lens  >=2.2   && <2.4-    , lens          ^>=5.3-    , network-uri   >=2.6.4 && <2.7-    , regex-tdfa    >=1.3.2 && <1.4-    , text          ^>=2.1-    , time          >=1.12  && <1.15-    , vector        >=0.13  && <0.14-    , yaml          >=0.11  && <0.12+    aeson >=2.2 && <2.4,+    attoparsec >=0.14 && <0.15,+    base >=4.21 && <5,+    bytestring >=0.11 && <0.13,+    cmark-gfm ^>=0.2,+    containers >=0.6 && <0.8,+    dhall >=1.41 && <1.43,+    directory >=1.3 && <1.4,+    filepath >=1.4 && <1.6,+    frontmatter >=0.1 && <0.2,+    generic-lens >=2.2 && <2.4,+    lens ^>=5.3,+    network-uri >=2.6.4 && <2.7,+    regex-tdfa >=1.3.2 && <1.4,+    scientific >=0.3 && <0.4,+    text ^>=2.1,+    time >=1.12 && <1.15,+    vector >=0.13 && <0.14,+    yaml >=0.11 && <0.12,  test-suite okf-core-test-  import:         common-options-  type:           exitcode-stdio-1.0-  main-is:        Main.hs+  import: common-options+  type: exitcode-stdio-1.0+  main-is: Main.hs   hs-source-dirs: test   build-depends:-    , aeson-    , base          >=4.20 && <5-    , containers    >=0.6  && <0.8-    , dhall         >=1.41 && <1.43-    , directory-    , filepath-    , generic-lens  >=2.2  && <2.4-    , lens          ^>=5.3-    , okf-core-    , temporary-    , text          ^>=2.1-    , time          >=1.12 && <1.15+    aeson,+    base >=4.21 && <5,+    containers >=0.6 && <0.8,+    dhall >=1.41 && <1.43,+    directory,+    filepath,+    generic-lens >=2.2 && <2.4,+    lens ^>=5.3,+    okf-core,+    temporary,+    text ^>=2.1,+    time >=1.12 && <1.15,
+ src/Okf/Exception.hs view
@@ -0,0 +1,11 @@+-- | Catch synchronous failures while preserving asynchronous cancellation.+module Okf.Exception (catchSynchronous) where++import Control.Exception (SomeAsyncException, SomeException, catch, fromException, throwIO)++catchSynchronous :: IO a -> (SomeException -> IO a) -> IO a+catchSynchronous action handler =+  action `catch` \exception ->+    case fromException exception :: Maybe SomeAsyncException of+      Just _ -> throwIO exception+      Nothing -> handler exception
src/Okf/Index.hs view
@@ -151,7 +151,7 @@ -- caller, so a stray @.DS_Store@ never reaches a committed index. renderIndex :: [FilePath] -> [FilePath] -> [Concept] -> Text renderIndex subdirectories files concepts =-  Text.intercalate "\n" (filter (not . Text.null) [subdirectorySection, fileSection, conceptSections]) <> "\n"+  Text.intercalate "\n" (filter (not . Text.null) [subdirectorySection, fileSection, conceptSections])   where     sortedSubdirectories = List.sort subdirectories     subdirectorySection@@ -202,9 +202,10 @@ renderRootIndexText Nothing subdirectories files concepts =   renderIndex subdirectories files concepts renderRootIndexText (Just versionText) subdirectories files concepts =-  Text.unlines ["---", "okf_version: \"" <> escaped versionText <> "\"", "---", ""]-    <> renderIndex subdirectories files concepts+  Text.unlines ["---", "okf_version: \"" <> escaped versionText <> "\"", "---"]+    <> (if Text.null body then "" else "\n" <> body)   where+    body = renderIndex subdirectories files concepts     -- The only two characters that can end a double-quoted YAML scalar early.     -- A parsed version can contain neither; a preserved raw one might.     escaped = Text.replace "\"" "\\\"" . Text.replace "\\" "\\\\"
src/Okf/Log.hs view
@@ -6,8 +6,10 @@     LogParseError (..),     LogValidationError (..),     appendLogEntry,+    insertLogEntry,     logErrorIsStructural,     parseLog,+    renderLogDiff,     serializeLog,     validateLog,   )@@ -15,8 +17,10 @@  import CMarkGFM qualified import Data.Char qualified as Char+import Data.List qualified as List import Data.Text qualified as Text import Data.Time (Day, defaultTimeLocale, parseTimeM)+import Numeric (showOct) import Okf.Markdown (markdownOptions) import Okf.Prelude @@ -54,6 +58,8 @@   deriving stock (Generic, Eq, Show)  -- | Parse Markdown into the log model. Structural validation is separate.+-- This model omits other Markdown blocks and source formatting; use+-- 'insertLogEntry' to modify an existing file without losing that content. parseLog :: Text -> Log parseLog markdown =   finish (foldl' step emptyBuild topLevelNodes)@@ -199,6 +205,74 @@       | dateText > logDate day = newDay : day : rest       | otherwise = day : insertDay rest +-- | Insert into the original Markdown without rendering historical content.+-- Source positions come from top-level headings, so heading-like text inside+-- code, HTML, lists and block quotes cannot become an insertion boundary.+-- Unsupported or ambiguous structure is rejected before a caller writes it.+insertLogEntry :: Text -> LogEntry -> Text -> Either Text Text+insertLogEntry dateText entry markdown = do+  unless (isIsoDate dateText) (Left "use a real calendar date in YYYY-MM-DD form")+  when (Text.any (== '\r') (Text.replace "\r\n" "" markdown)) $+    Left "bare CR line endings are unsupported; use LF or CRLF"+  title <- case titles of+    [node] -> Right node+    _ -> Left "expected exactly one top-level log title (# heading)"+  titlePosition <- headingPosition title+  days <- for dateHeadings $ \node -> do+    pos <- headingPosition node+    let day = plainText node+    unless (isIsoDate day) (Left ("non-date level-two heading: " <> day))+    unless (CMarkGFM.startLine pos > CMarkGFM.endLine titlePosition) $+      Left "date headings must follow the log title"+    pure (day, pos)+  unless (and (zipWith (>) (fmap fst days) (drop 1 (fmap fst days)))) $+    Left "date headings must be unique and ordered newest first"+  -- Parsing the generated fragment also rejects messages that introduce extra+  -- headings or entries. Compare the complete parsed result below to catch an+  -- insertion swallowed by an unclosed code fence or HTML block at EOF.+  case CMarkGFM.commonmarkToNode markdownOptions [] fragment of+    CMarkGFM.Node _ _ [CMarkGFM.Node _ (CMarkGFM.HEADING 1) _, CMarkGFM.Node _ (CMarkGFM.HEADING 2) _, CMarkGFM.Node _ (CMarkGFM.LIST _) [_]] -> pure ()+    _ -> Left "kind and message must form a single log entry"+  let (offset, insertion) = case List.find ((== dateText) . fst) days of+        Just (_, pos) -> (afterLine (CMarkGFM.endLine pos), renderedEntry)+        Nothing ->+          ( maybe+              (Text.length markdown)+              (beforeLine . CMarkGFM.startLine . snd)+              (List.find ((< dateText) . fst) days),+            "## " <> dateText <> newline <> renderedEntry+          )+      (before, after) = Text.splitAt offset markdown+      separator+        | Text.null before || (newline <> newline) `Text.isSuffixOf` before = ""+        | newline `Text.isSuffixOf` before = newline+        | otherwise = newline <> newline+      result = before <> separator <> insertion <> newline <> (if Text.null after then "" else newline) <> after+      parsedResult = parseLog result+  -- Read the new entry in context: reference-style links may resolve against+  -- definitions in the original Markdown rather than in the isolated fragment.+  insertedEntry <- case [newEntry | LogDay day (newEntry : _) <- logDays parsedResult, day == dateText] of+    [newEntry] -> Right newEntry+    _ -> Left "inserted entry is not visible under its date heading"+  unless (parsedResult == appendLogEntry dateText insertedEntry (parseLog markdown)) $+    Left "cannot safely insert an entry into this Markdown structure"+  pure result+  where+    CMarkGFM.Node _ _ nodes = CMarkGFM.commonmarkToNode markdownOptions [] markdown+    titles = [node | node@(CMarkGFM.Node _ (CMarkGFM.HEADING 1) _) <- nodes]+    dateHeadings = [node | node@(CMarkGFM.Node _ (CMarkGFM.HEADING 2) _) <- nodes]+    headingPosition (CMarkGFM.Node (Just pos) _ _) = Right pos+    headingPosition _ = Left "log heading has no source position"+    newline = if "\r\n" `Text.isInfixOf` markdown then "\r\n" else "\n"+    renderedEntry = case entry of+      LogEntry (Just kind) body -> "* **" <> kind <> "**: " <> body+      LogEntry Nothing body -> "* " <> body+    fragment = "# Log\n\n## " <> dateText <> "\n" <> renderedEntry <> "\n"+    -- Keep CRs and all original line terminators in the slices. Only line+    -- numbers are used; cmark's byte-based columns need no Text conversion.+    afterLine line = min (Text.length markdown) (sum (fmap ((+ 1) . Text.length) (take line (Text.splitOn "\n" markdown))))+    beforeLine line = afterLine (line - 1)+ dropKindSeparator :: Text -> Text dropKindSeparator text =   Text.stripStart@@ -214,6 +288,61 @@   | Text.null text = "\n"   | "\n" `Text.isSuffixOf` text = text   | otherwise = text <> "\n"++-- | Show an exact unified diff against the original source, or @/dev/null@+-- for a new file. A single hunk spans every change with up to three context+-- lines at each end. Line terminators (including CRLF and absent final LF)+-- participate in comparison, so formatting changes cannot be hidden.+renderLogDiff :: FilePath -> Maybe Text -> Text -> Text+renderLogDiff path original updated =+  "--- "+    <> maybe "/dev/null" (const displayPath) original+    <> "\n"+    <> "+++ "+    <> displayPath+    <> "\n"+    <> if old == new+      then ""+      else+        "@@ -"+          <> range start (length before + length removed + length after)+          <> " +"+          <> range start (length before + length added + length after)+          <> " @@\n"+          <> foldMap (renderLine " ") before+          <> foldMap (renderLine "-") removed+          <> foldMap (renderLine "+") added+          <> foldMap (renderLine " ") after+  where+    -- Quote unusual path characters using Git's quoted-path convention.+    displayPath+      | any (\c -> c == '"' || c == '\\' || Char.isControl c) path = "\"" <> Text.concatMap quoteChar (Text.pack path) <> "\""+      | otherwise = Text.pack path+    quoteChar '"' = "\\\""+    quoteChar '\\' = "\\\\"+    quoteChar c+      | Char.ord c < 32 || Char.ord c == 127 =+          let octal = showOct (Char.ord c) ""+           in "\\" <> Text.pack (replicate (3 - length octal) '0' <> octal)+      | otherwise = Text.singleton c+    old = sourceLines (fromMaybe "" original)+    new = sourceLines updated+    prefixLength = length (takeWhile (uncurry (==)) (zip old new))+    oldRest = drop prefixLength old+    newRest = drop prefixLength new+    suffixLength = length (takeWhile (uncurry (==)) (zip (reverse oldRest) (reverse newRest)))+    before = drop (max 0 (prefixLength - 3)) (take prefixLength old)+    after = take 3 (drop (length oldRest - suffixLength) oldRest)+    removed = take (length oldRest - suffixLength) oldRest+    added = take (length newRest - suffixLength) newRest+    start = prefixLength - length before+    range offset count = Text.pack (show (if count == 0 then offset else offset + 1)) <> "," <> Text.pack (show count)+    renderLine marker line = marker <> line <> if "\n" `Text.isSuffixOf` line then "" else "\n\\ No newline at end of file\n"+    sourceLines text+      | Text.null text = []+      | otherwise =+          let (line, rest) = Text.breakOn "\n" text+           in if Text.null rest then [line] else (line <> "\n") : sourceLines (Text.drop 1 rest)  isIsoDate :: Text -> Bool isIsoDate value =
src/Okf/Profile.hs view
@@ -12,4641 +12,5651 @@ module Okf.Profile   ( -- * Descriptor     ProfileSpec (..),-    FrontmatterRules (..),-    FieldCondition (..),-    HandleReferenceRule (..),-    PathReferenceRule (..),-    FieldRule (..),-    NestedRules (..),-    NestedFieldRule (..),-    Cardinality (..),-    FieldFormat (..),-    TypeRule (..),-    FieldPath (..),-    FieldPathSegment (..),-    loadProfileFile,-    decodeProfileExpr,-    profileFieldDescription,-    CompiledProfile,-    ProfileDefinitionError (..),-    compileProfile,-    compiledProfileSpec,-    compiledProfileRequiredBundleVersion,-    profileFieldDescriptionForType,--    -- * Compiled rule inspection--    -- | A read-only window onto what a compiled profile actually demands. The-    -- rule types are abstract on purpose: read them through the accessors below-    -- so that later profile features can extend the compiled encoding without-    -- breaking consumers.-    ---    -- Two encodings are easy to misread and are worth stating up front. An-    -- __empty presence-clause list means the key is optional__, not that it is-    -- unconstrained; and an __empty allowed-value list means unconstrained__,-    -- not that no value is permitted.-    EffectiveFieldRule,-    PresenceClause,-    FieldRequirement (..),-    fieldRulePresenceClauses,-    presenceClauseRequirement,-    presenceClauseCondition,-    fieldRuleDescription,-    fieldRuleAllowedValues,-    fieldRuleCardinality,-    fieldRuleFormat,-    fieldRuleReference,-    fieldRuleUniqueBy,-    fieldRulePath,-    fieldRuleElementFields,-    fieldRuleObjectFields,-    compiledProfileTypeNames,-    compiledProfileBaseRules,-    compiledProfileRulesForType,-    renderCardinalityName,-    renderFieldFormatName,--    -- * Validation-    DocumentId (..),-    parseDocumentId,-    renderDocumentId,-    documentIdsInBundle,-    nextDocumentId,-    ProfileViolation (..),-    validateProfile,-    validateProfileWith,-    validateProfileVersion,--    -- * Body inspection-    schemaSectionColumns,-  )-where--import CMarkGFM qualified-import Control.Exception (SomeException, catch)-import Data.Aeson (ToJSON (..), object, (.=))-import Data.Aeson qualified as Aeson-import Data.Aeson.Key qualified as Aeson.Key-import Data.Aeson.KeyMap qualified as Aeson.KeyMap-import Data.Char (isAsciiLower, isAsciiUpper)-import Data.List qualified as List-import Data.Map.Strict (Map)-import Data.Map.Strict qualified as Map-import Data.Maybe (catMaybes, mapMaybe)-import Data.Set qualified as Set-import Data.Text qualified as Text-import Data.Text.Read qualified as Text.Read-import Data.Time.Calendar (Day)-import Data.Time.Clock (UTCTime)-import Data.Time.Format.ISO8601 (iso8601ParseM)-import Data.Vector qualified as Vector-import Data.Void (Void)-import Dhall (FromDhall (..), auto, genericAutoWith)-import Dhall qualified-import Dhall.Core (Expr)-import Dhall.Core qualified as Dhall.Core-import Dhall.Map qualified as Dhall.Map-import Dhall.Src (Src)-import Network.URI (parseURI, uriScheme)-import Numeric.Natural (Natural)--- Imported qualified: 'Okf.Actor.HumanActor' is a constructor of 'Actor.Actor'--- and 'HumanActor' is a constructor of 'FieldFormat', so an unqualified import--- makes the two ambiguous.-import Okf.Actor qualified as Actor-import Okf.Bundle-  ( BundleInventory,-    Concept,-    bundleInventoryMember,-    bundleInventoryOfConcepts,-    conceptDocument,-    conceptIdOf,-    conceptResource,-    conceptType,-  )-import Okf.ConceptId (ConceptId, conceptIdFromFilePath, renderConceptId)-import Okf.Document-  ( Frontmatter,-    coreFrontmatterFields,-    fieldsSupersededInV02,-    frontmatterKeys,-    frontmatterLookup,-  )-import Okf.Index-  ( OkfVersion (..),-    VersionDeclaration (..),-    parseOkfVersion,-    renderOkfVersion,-    supportedOkfVersion,-  )-import Okf.Markdown (markdownOptions)-import Okf.Path (PathReference (..), classifyPathReference)--- 'List' and 'Object' are 'Cardinality' constructors here; the names aeson uses--- for the corresponding 'Value' constructors are reached as 'Aeson.Array' and--- 'Aeson.Object'.-import Okf.Prelude hiding (List, Object, (.=))-import Okf.Validation (ValidationProfile (..))-import System.FilePath qualified as FilePath-import Text.Regex.TDFA (Regex, defaultCompOpt, defaultExecOpt)-import Text.Regex.TDFA.Text qualified as Regex.Text-import "generic-lens" Data.Generics.Labels ()---- | A complete house profile. @description@ concisely documents the profile's--- identity. @guidance@ is multiline Markdown prescribing how authors should do--- the work. Neither is checked against a bundle or executed, and neither can--- produce a 'ProfileViolation'.------ @requireBundleVersion@ and @okfVersion@ are easy to confuse and answer--- different questions. @okfVersion@ says which version's rules /this profile--- writes/, and 'compileProfile' checks the profile's own rules against it.--- @requireBundleVersion@ says what the profile demands of a /bundle/: @Just--- \"0.2\"@ means the bundle's root @index.md@ must declare @okf_version@ at 0.2--- or later, checked by 'validateProfileVersion'. Neither constrains the other.-data ProfileSpec = ProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    guidance :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !FrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    requireBundleVersion :: !(Maybe Text),-    types :: ![TypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | Frontmatter keys the profile expects on every concept. @required@ is always--- checked, @recommended@ only under 'StrictAuthoring', and @optional@ never:--- an optional key is fully validated whenever it is present and its absence is--- never a deviation in any mode.-data FrontmatterRules = FrontmatterRules-  { required :: ![FieldRule],-    recommended :: ![FieldRule],-    optional :: ![FieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | A same-scope predicate controlling whether a field's presence rule applies.--- The source field must compile to a closed scalar textual vocabulary.-data FieldCondition = FieldCondition-  { field :: !Text,-    hasValue :: ![Text]-  }-  deriving stock (Generic, Eq, Ord, Show)-  deriving anyclass (FromDhall)---- | A top-level field whose textual values point either to a local document--- handle with one prefix or to an absolute URI with an explicitly allowed--- scheme. External targets are never resolved by okf.-data HandleReferenceRule = HandleReferenceRule-  { localPrefix :: !Text,-    externalUriSchemes :: ![Text],-    allowSelf :: !Bool,-    allowLocal :: !Bool,-    externalUriPattern :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Ord, Show)-  deriving anyclass (FromDhall)---- | A field whose values name a path or URI per OKF v0.2 specification §6.2: an--- absolute URL, a bundle-relative path beginning with @\/@, or an ordinary--- relative path resolved against the concept's own directory.------ Deliberately distinct from 'HandleReferenceRule'. A handle resolves against--- the bundle's document-ID index and fails by carrying the wrong prefix or--- having no owner; a path resolves against the concept tree and fails by not--- being a §6.2 shape, by climbing above the bundle root, or by naming a concept--- that is not there. Declaring both on one rule is a definition error.------ An empty @externalUriSchemes@ means no absolute URL is permitted at all, so a--- separate "must be a path, never a URL" flag would say nothing new. Which--- bundle paths okf can resolve depends on the entry point: 'validateProfileWith'--- resolves every file the bundle holds, including §6.3's--- @references\/attesters\/revenue.py@, while 'validateProfile' is handed--- concepts alone and so resolves @.md@ targets only.-data PathReferenceRule = PathReferenceRule-  { externalUriSchemes :: ![Text],-    allowSelf :: !Bool-  }-  deriving stock (Generic, Eq, Ord, Show)-  deriving anyclass (FromDhall)---- | One documented frontmatter key. The description is prose for humans and is--- never checked against a bundle.------ @elementFields@ and @objectFields@ describe two different shapes.--- @elementFields@ constrains the record inside /each element of a list/;--- @objectFields@ constrains the record that /is/ the value. Declaring both means--- either spelling is accepted and both are checked against the same member--- rules, which is how a profile describes the OKF v0.2 @verified@ key.-data FieldRule = FieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe FieldFormat),-    elementFields :: !(Maybe NestedRules),-    objectFields :: !(Maybe NestedRules),-    reference :: !(Maybe HandleReferenceRule),-    path :: !(Maybe PathReferenceRule),-    when :: !(Maybe FieldCondition),-    uniqueBy :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | Rules for the flat object stored in each element of a list-valued field, or--- in the mapping that is the value of an object-valued field. The nested rule--- type has neither an @elementFields@ nor an @objectFields@ member, which makes--- the public descriptor depth-bounded rather than recursive.-data NestedRules = NestedRules-  { required :: ![NestedFieldRule],-    recommended :: ![NestedFieldRule],-    optional :: ![NestedFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | One field inside a list element record or an object-valued mapping. It--- carries @path@ because @sources[].resource@ is the motivating path-valued--- field of §6.2 and lives inside a list element; it deliberately carries no--- @reference@, because no v0.2 field names a document handle at nested scope.-data NestedFieldRule = NestedFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe FieldFormat),-    path :: !(Maybe PathReferenceRule),-    when :: !(Maybe FieldCondition),-    reference :: !(Maybe HandleReferenceRule)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | Whether a key must be a single value, a non-empty list, a mapping, or any--- of them. 'Object' is placed last so the derived 'Ord' keeps the relative--- order of the three published alternatives, which the definition-error sort key--- relies on.-data Cardinality = Any | Scalar | List | Object-  deriving stock (Generic, Eq, Ord, Show)---- | Decoded from the three-alternative published union in--- @okf-core\/dhall\/Cardinality.dhall@. 'Object' is deliberately unreachable--- from Dhall: it is produced only by compilation, when a rule declares--- @objectFields@. Adding an alternative to the published union would change the--- type of every value written against it and would break descriptors pinned to--- the previous schema, which no record-level fallback decoder can repair,--- because every frozen generation in the chain refers to this same type. An--- author who wants to say "this key must be a mapping" and nothing more writes--- @objectFields = Some NestedRules::{=}@.-instance FromDhall Cardinality where-  autoWith _normalizer =-    Dhall.union-      ( (Any <$ Dhall.constructor "Any" Dhall.unit)-          <> (Scalar <$ Dhall.constructor "Scalar" Dhall.unit)-          <> (List <$ Dhall.constructor "List" Dhall.unit)-      )---- | A named value format. Formats constrain present values but do not imply--- that a field must be present.------ The first five constrain text. 'Actor' and 'HumanActor' constrain text against--- the OKF v0.2 actor convention of specification §7, classified by--- 'Okf.Actor.parseActor'. 'Integer', 'NonNegativeInteger', and 'Boolean'--- constrain a value that is not text at all; declaring one of them refines an--- unspecified cardinality to 'Scalar', because otherwise a numeric or boolean--- key is reported missing before its value is ever examined.------ The OKF v0.2 alternatives are appended after 'DocumentHandle' so the derived--- 'Ord' keeps the relative order of the original five, which the--- definition-error sort key relies on.-data FieldFormat-  = Rfc3339Utc-  | Date-  | Uri-  | UriWithScheme Text-  | DocumentHandle Text-  | Actor-  | HumanActor-  | Integer-  | NonNegativeInteger-  | Boolean-  deriving stock (Generic, Eq, Ord, Show)-  deriving anyclass (FromDhall)---- | One rule per allowed concept @type@ string. @guidance@ adds authoring--- procedure specific to this type; it is documentary and never executed.-data TypeRule = TypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    guidance :: !(Maybe Text),-    frontmatter :: !FrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)---- | Decode @type_@ from the Dhall field @type@ by stripping the trailing--- underscore; all other fields map by their exact name. (Mirrors how--- 'Okf.Bundle' uses a @type_@ field to avoid clashing with the @type@ keyword.)-instance FromDhall TypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | Encode a profile so tooling can consume the same descriptor okf reads.--- Written by hand rather than derived so the key order is stable and, more--- importantly, so 'TypeRule' emits @type@ rather than the Haskell field name--- @type_@ — matching the Dhall field and how 'Okf.Graph.Node' already encodes.-instance ToJSON ProfileSpec where-  toJSON ProfileSpec {name, description, guidance, okfVersion, frontmatter, allowUnknownTypes, allowUnknownFields, idField, requireBundleVersion, types = typeRules} =-    object-      [ "name" .= name,-        "description" .= description,-        "guidance" .= guidance,-        "okfVersion" .= okfVersion,-        "requireBundleVersion" .= requireBundleVersion,-        "allowUnknownTypes" .= allowUnknownTypes,-        "allowUnknownFields" .= allowUnknownFields,-        "idField" .= idField,-        "frontmatter" .= frontmatter,-        "types" .= typeRules-      ]--instance ToJSON FrontmatterRules where-  toJSON FrontmatterRules {required, recommended, optional} =-    object-      [ "required" .= required,-        "recommended" .= recommended,-        "optional" .= optional-      ]--instance ToJSON FieldCondition where-  toJSON FieldCondition {field = fieldName, hasValue} =-    object-      [ "field" .= fieldName,-        "hasValue" .= hasValue-      ]--instance ToJSON HandleReferenceRule where-  toJSON HandleReferenceRule {localPrefix, externalUriSchemes, allowSelf, allowLocal, externalUriPattern} =-    object-      [ "localPrefix" .= localPrefix,-        "externalUriSchemes" .= externalUriSchemes,-        "allowSelf" .= allowSelf,-        "allowLocal" .= allowLocal,-        "externalUriPattern" .= externalUriPattern-      ]--instance ToJSON PathReferenceRule where-  toJSON PathReferenceRule {externalUriSchemes, allowSelf} =-    object-      [ "externalUriSchemes" .= externalUriSchemes,-        "allowSelf" .= allowSelf-      ]--instance ToJSON FieldRule where-  toJSON FieldRule {field = fieldName, description, allowedValues, cardinality, format, elementFields, objectFields, reference, path = pathRule, when = condition, uniqueBy} =-    object-      [ "field" .= fieldName,-        "description" .= description,-        "allowedValues" .= allowedValues,-        "cardinality" .= cardinality,-        "format" .= format,-        "elementFields" .= elementFields,-        "reference" .= reference,-        "when" .= condition,-        -- Appended rather than placed beside @elementFields@, so that the list-        -- reads as "the keys this instance has always emitted, then the ones-        -- added since". A consumer keys on names, not position.-        "objectFields" .= objectFields,-        "path" .= pathRule,-        "uniqueBy" .= uniqueBy-      ]--instance ToJSON NestedRules where-  toJSON NestedRules {required, recommended, optional} =-    object-      [ "required" .= required,-        "recommended" .= recommended,-        "optional" .= optional-      ]--instance ToJSON NestedFieldRule where-  toJSON NestedFieldRule {field = fieldName, description, allowedValues, cardinality, format, path = pathRule, when = condition, reference} =-    object-      [ "field" .= fieldName,-        "description" .= description,-        "allowedValues" .= allowedValues,-        "cardinality" .= cardinality,-        "format" .= format,-        "when" .= condition,-        -- Appended for the same reason 'FieldRule' appends @objectFields@.-        "path" .= pathRule,-        "reference" .= reference-      ]--instance ToJSON Cardinality where-  toJSON = String . cardinalityName--cardinalityName :: Cardinality -> Text-cardinalityName = \case-  Any -> "any"-  Scalar -> "scalar"-  List -> "list"-  Object -> "object"--instance ToJSON FieldFormat where-  toJSON = \case-    Rfc3339Utc -> String "rfc3339-utc"-    Date -> String "date"-    Uri -> String "uri"-    UriWithScheme scheme -> object ["uriWithScheme" .= scheme]-    DocumentHandle prefix -> object ["documentHandle" .= prefix]-    Actor -> String "actor"-    HumanActor -> String "human-actor"-    Integer -> String "integer"-    NonNegativeInteger -> String "non-negative-integer"-    Boolean -> String "boolean"--instance ToJSON TypeRule where-  toJSON-    TypeRule-      { type_ = ruleType,-        description,-        guidance,-        frontmatter,-        pathPattern,-        resourceScheme,-        requireSchemaSection,-        schemaColumns,-        idPrefix-      } =-      object-        [ "type" .= ruleType,-          "description" .= description,-          "guidance" .= guidance,-          "frontmatter" .= frontmatter,-          "pathPattern" .= pathPattern,-          "resourceScheme" .= resourceScheme,-          "requireSchemaSection" .= requireSchemaSection,-          "schemaColumns" .= schemaColumns,-          "idPrefix" .= idPrefix-        ]---- | The complete descriptor generation published by okf-core 0.8.0.0, frozen--- immediately before profile and type guidance were added. Every reachable--- record and union is copied here so future schema additions cannot change the--- Dhall type this decoder accepts. Exercised by--- @okf-core/test/fixtures/profiles/pre-guidance-0.8.0.0.dhall@.-data PreGuidanceCardinality-  = PreGuidanceAny-  | PreGuidanceScalar-  | PreGuidanceList-  deriving stock (Generic, Eq, Ord, Show)--instance FromDhall PreGuidanceCardinality where-  autoWith _normalizer =-    Dhall.union-      ( (PreGuidanceAny <$ Dhall.constructor "Any" Dhall.unit)-          <> (PreGuidanceScalar <$ Dhall.constructor "Scalar" Dhall.unit)-          <> (PreGuidanceList <$ Dhall.constructor "List" Dhall.unit)-      )--data PreGuidanceFieldFormat-  = PreGuidanceRfc3339Utc-  | PreGuidanceDate-  | PreGuidanceUri-  | PreGuidanceUriWithScheme Text-  | PreGuidanceDocumentHandle Text-  | PreGuidanceActor-  | PreGuidanceHumanActor-  | PreGuidanceInteger-  | PreGuidanceNonNegativeInteger-  | PreGuidanceBoolean-  deriving stock (Generic, Eq, Ord, Show)--instance FromDhall PreGuidanceFieldFormat where-  autoWith _normalizer =-    Dhall.union-      ( (PreGuidanceRfc3339Utc <$ Dhall.constructor "Rfc3339Utc" Dhall.unit)-          <> (PreGuidanceDate <$ Dhall.constructor "Date" Dhall.unit)-          <> (PreGuidanceUri <$ Dhall.constructor "Uri" Dhall.unit)-          <> (PreGuidanceUriWithScheme <$> Dhall.constructor "UriWithScheme" Dhall.auto)-          <> (PreGuidanceDocumentHandle <$> Dhall.constructor "DocumentHandle" Dhall.auto)-          <> (PreGuidanceActor <$ Dhall.constructor "Actor" Dhall.unit)-          <> (PreGuidanceHumanActor <$ Dhall.constructor "HumanActor" Dhall.unit)-          <> (PreGuidanceInteger <$ Dhall.constructor "Integer" Dhall.unit)-          <> (PreGuidanceNonNegativeInteger <$ Dhall.constructor "NonNegativeInteger" Dhall.unit)-          <> (PreGuidanceBoolean <$ Dhall.constructor "Boolean" Dhall.unit)-      )--data PreGuidanceFieldCondition = PreGuidanceFieldCondition-  { field :: !Text,-    hasValue :: ![Text]-  }-  deriving stock (Generic, Eq, Ord, Show)-  deriving anyclass (FromDhall)--data PreGuidanceHandleReferenceRule = PreGuidanceHandleReferenceRule-  { localPrefix :: !Text,-    externalUriSchemes :: ![Text],-    allowSelf :: !Bool,-    allowLocal :: !Bool,-    externalUriPattern :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Ord, Show)-  deriving anyclass (FromDhall)--data PreGuidancePathReferenceRule = PreGuidancePathReferenceRule-  { externalUriSchemes :: ![Text],-    allowSelf :: !Bool-  }-  deriving stock (Generic, Eq, Ord, Show)-  deriving anyclass (FromDhall)--data PreGuidanceFieldRule = PreGuidanceFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !PreGuidanceCardinality,-    format :: !(Maybe PreGuidanceFieldFormat),-    elementFields :: !(Maybe PreGuidanceNestedRules),-    objectFields :: !(Maybe PreGuidanceNestedRules),-    reference :: !(Maybe PreGuidanceHandleReferenceRule),-    path :: !(Maybe PreGuidancePathReferenceRule),-    when :: !(Maybe PreGuidanceFieldCondition),-    uniqueBy :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreGuidanceNestedRules = PreGuidanceNestedRules-  { required :: ![PreGuidanceNestedFieldRule],-    recommended :: ![PreGuidanceNestedFieldRule],-    optional :: ![PreGuidanceNestedFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreGuidanceNestedFieldRule = PreGuidanceNestedFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !PreGuidanceCardinality,-    format :: !(Maybe PreGuidanceFieldFormat),-    path :: !(Maybe PreGuidancePathReferenceRule),-    when :: !(Maybe PreGuidanceFieldCondition),-    reference :: !(Maybe PreGuidanceHandleReferenceRule)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreGuidanceFrontmatterRules = PreGuidanceFrontmatterRules-  { required :: ![PreGuidanceFieldRule],-    recommended :: ![PreGuidanceFieldRule],-    optional :: ![PreGuidanceFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreGuidanceTypeRule = PreGuidanceTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !PreGuidanceFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall PreGuidanceTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)--data PreGuidanceProfileSpec = PreGuidanceProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !PreGuidanceFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    requireBundleVersion :: !(Maybe Text),-    types :: ![PreGuidanceTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | The okf 0.2.x profile record: frontmatter keys were bare strings and--- nothing carried a description. Decoded only as a fallback, so descriptors--- written before descriptions existed keep loading unchanged. Deliberately--- private and deliberately frozen — it is a record of a retired shape, not a--- second profile model. Exercised by--- @okf-core\/test\/fixtures\/profiles\/legacy-0.2.dhall@.-data LegacyProfileSpec = LegacyProfileSpec-  { name :: !Text,-    okfVersion :: !Text,-    frontmatter :: !LegacyFrontmatterRules,-    allowUnknownTypes :: !Bool,-    idField :: !(Maybe Text),-    types :: ![LegacyTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | The okf 0.2.x frontmatter record: two lists of bare key names.-data LegacyFrontmatterRules = LegacyFrontmatterRules-  { required :: ![Text],-    recommended :: ![Text]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | The okf 0.2.x per-@type@ rule: today's 'TypeRule' without descriptions or--- type-specific frontmatter.-data LegacyTypeRule = LegacyTypeRule-  { type_ :: !Text,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall LegacyTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The five-alternative published format union, frozen before the OKF v0.2--- value formats were added.------ Unlike every other frozen shape below this is a /union/ rather than a record.--- A Dhall union value carries its full alternative set in its type, so a--- descriptor pinned to the five-alternative--- @okf-core\/dhall\/FieldFormat.dhall@ does not typecheck against the current--- decoder, and no record-level fallback can repair that: every frozen generation--- would still refer to the widened 'FieldFormat'. Every frozen generation below--- therefore refers to this type instead.------ The instance is hand-written rather than derived so that the Dhall alternative--- names stay @Rfc3339Utc@ and friends while the Haskell constructors stay--- distinct from the current type's.-data PreV02FieldFormat-  = LegacyRfc3339Utc-  | LegacyDate-  | LegacyUri-  | LegacyUriWithScheme Text-  | LegacyDocumentHandle Text-  deriving stock (Generic, Eq, Ord, Show)--instance FromDhall PreV02FieldFormat where-  autoWith _normalizer =-    Dhall.union-      ( (LegacyRfc3339Utc <$ Dhall.constructor "Rfc3339Utc" Dhall.unit)-          <> (LegacyDate <$ Dhall.constructor "Date" Dhall.unit)-          <> (LegacyUri <$ Dhall.constructor "Uri" Dhall.unit)-          <> (LegacyUriWithScheme <$> Dhall.constructor "UriWithScheme" Dhall.auto)-          <> (LegacyDocumentHandle <$> Dhall.constructor "DocumentHandle" Dhall.auto)-      )--upgradePreV02FieldFormat :: PreV02FieldFormat -> FieldFormat-upgradePreV02FieldFormat = \case-  LegacyRfc3339Utc -> Rfc3339Utc-  LegacyDate -> Date-  LegacyUri -> Uri-  LegacyUriWithScheme scheme -> UriWithScheme scheme-  LegacyDocumentHandle prefix -> DocumentHandle prefix---- | The complete 0.7.0.0 descriptor generation, frozen before nested--- document-reference policies and record-list uniqueness were added. Every--- record that directly or transitively contains one of the grown records is--- copied so a descriptor pinned to 0.7.0.0 remains decodable as one closed--- Dhall type.-data PreNestedReferenceHandleReferenceRule = PreNestedReferenceHandleReferenceRule-  { localPrefix :: !Text,-    externalUriSchemes :: ![Text],-    allowSelf :: !Bool-  }-  deriving stock (Generic, Eq, Ord, Show)-  deriving anyclass (FromDhall)--data PreNestedReferenceFieldRule = PreNestedReferenceFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe FieldFormat),-    elementFields :: !(Maybe PreNestedReferenceNestedRules),-    objectFields :: !(Maybe PreNestedReferenceNestedRules),-    reference :: !(Maybe PreNestedReferenceHandleReferenceRule),-    path :: !(Maybe PathReferenceRule),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreNestedReferenceNestedRules = PreNestedReferenceNestedRules-  { required :: ![PreNestedReferenceNestedFieldRule],-    recommended :: ![PreNestedReferenceNestedFieldRule],-    optional :: ![PreNestedReferenceNestedFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreNestedReferenceNestedFieldRule = PreNestedReferenceNestedFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe FieldFormat),-    path :: !(Maybe PathReferenceRule),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreNestedReferenceFrontmatterRules = PreNestedReferenceFrontmatterRules-  { required :: ![PreNestedReferenceFieldRule],-    recommended :: ![PreNestedReferenceFieldRule],-    optional :: ![PreNestedReferenceFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreNestedReferenceProfileSpec = PreNestedReferenceProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !PreNestedReferenceFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    requireBundleVersion :: !(Maybe Text),-    types :: ![PreNestedReferenceTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreNestedReferenceTypeRule = PreNestedReferenceTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !PreNestedReferenceFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall PreNestedReferenceTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The complete descriptor generation frozen before a profile could require its--- bundle to declare an OKF version. This is the immediately preceding public--- descriptor generation: it is today's shape minus the @requireBundleVersion@--- member on the top-level record. That member is the only difference, so every--- rule record, every type rule, and every union is unchanged and is shared--- rather than copied — the freezing rule of--- @docs\/adr\/11-growing-the-profile-descriptor-language.md@ is about the--- descriptor as a whole, and a generation that changes one record copies only--- what changed. Exercised by--- @okf-core\/test\/fixtures\/profiles\/pre-bundle-version.dhall@.-data PreBundleVersionProfileSpec = PreBundleVersionProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !PreNestedReferenceFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    types :: ![PreNestedReferenceTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | The complete descriptor generation frozen before path-valued reference--- rules were added: today's shape minus the @path@ member on 'FieldRule' and on--- 'NestedFieldRule'. Because that is a record addition rather than a union--- widening, 'Cardinality', 'FieldFormat', 'FieldCondition', and--- 'HandleReferenceRule' are unchanged by it and so are shared rather than--- copied; the two rule records and everything that contains them are copied.--- Exercised by @okf-core\/test\/fixtures\/profiles\/path-references-mp8-ep3.dhall@.-data PrePathProfileFieldRule = PrePathProfileFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe FieldFormat),-    elementFields :: !(Maybe PrePathProfileNestedRules),-    objectFields :: !(Maybe PrePathProfileNestedRules),-    reference :: !(Maybe PreNestedReferenceHandleReferenceRule),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PrePathProfileNestedRules = PrePathProfileNestedRules-  { required :: ![PrePathProfileNestedFieldRule],-    recommended :: ![PrePathProfileNestedFieldRule],-    optional :: ![PrePathProfileNestedFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PrePathProfileNestedFieldRule = PrePathProfileNestedFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe FieldFormat),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PrePathProfileFrontmatterRules = PrePathProfileFrontmatterRules-  { required :: ![PrePathProfileFieldRule],-    recommended :: ![PrePathProfileFieldRule],-    optional :: ![PrePathProfileFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PrePathProfileSpec = PrePathProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !PrePathProfileFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    types :: ![PrePathProfileTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PrePathProfileTypeRule = PrePathProfileTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !PrePathProfileFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall PrePathProfileTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The complete object-rule descriptor generation, frozen before the OKF v0.2--- value formats were added to 'FieldFormat'. Its records match the shape--- 'PrePathProfileFieldRule' froze — no @path@ member — and the further--- difference is that every @format@ member refers to the frozen--- five-alternative 'PreV02FieldFormat'. Exercised by--- @okf-core\/test\/fixtures\/profiles\/formats-mp8-ep2.dhall@.-data PreActorProfileFieldRule = PreActorProfileFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat),-    elementFields :: !(Maybe PreActorProfileNestedRules),-    objectFields :: !(Maybe PreActorProfileNestedRules),-    reference :: !(Maybe PreNestedReferenceHandleReferenceRule),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreActorProfileNestedRules = PreActorProfileNestedRules-  { required :: ![PreActorProfileNestedFieldRule],-    recommended :: ![PreActorProfileNestedFieldRule],-    optional :: ![PreActorProfileNestedFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreActorProfileNestedFieldRule = PreActorProfileNestedFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreActorProfileFrontmatterRules = PreActorProfileFrontmatterRules-  { required :: ![PreActorProfileFieldRule],-    recommended :: ![PreActorProfileFieldRule],-    optional :: ![PreActorProfileFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreActorProfileSpec = PreActorProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !PreActorProfileFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    types :: ![PreActorProfileTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreActorProfileTypeRule = PreActorProfileTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !PreActorProfileFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall PreActorProfileTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The complete optional-presence descriptor generation, frozen before object--- rules were added: it matches the shape before @objectFields@ was added to--- 'FieldRule'. 'Cardinality', 'HandleReferenceRule', and 'FieldCondition' are--- unchanged by every addition since and so are shared rather than copied; the--- nested rule types are copied because their @format@ member now refers to the--- frozen 'PreV02FieldFormat'. Exercised by--- @okf-core\/test\/fixtures\/profiles\/object-fields-mp8-ep1.dhall@.-data PreObjectProfileFieldRule = PreObjectProfileFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat),-    elementFields :: !(Maybe PreObjectProfileNestedRules),-    reference :: !(Maybe PreNestedReferenceHandleReferenceRule),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreObjectProfileNestedRules = PreObjectProfileNestedRules-  { required :: ![PreObjectProfileNestedFieldRule],-    recommended :: ![PreObjectProfileNestedFieldRule],-    optional :: ![PreObjectProfileNestedFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreObjectProfileNestedFieldRule = PreObjectProfileNestedFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreObjectProfileFrontmatterRules = PreObjectProfileFrontmatterRules-  { required :: ![PreObjectProfileFieldRule],-    recommended :: ![PreObjectProfileFieldRule],-    optional :: ![PreObjectProfileFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreObjectProfileSpec = PreObjectProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !PreObjectProfileFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    types :: ![PreObjectProfileTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreObjectProfileTypeRule = PreObjectProfileTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !PreObjectProfileFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall PreObjectProfileTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The complete reference-aware descriptor generation, frozen before the--- @optional@ presence list was added to 'FrontmatterRules' and 'NestedRules'.--- This is the immediately preceding public descriptor generation: it matches--- today's shape exactly apart from that third list, so every descriptor written--- as a record literal against the published schema keeps loading. Exercised by--- @okf-core\/test\/fixtures\/profiles\/document-references-ep3.dhall@.-data ReferenceProfileFieldRule = ReferenceProfileFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat),-    elementFields :: !(Maybe ReferenceProfileNestedRules),-    reference :: !(Maybe PreNestedReferenceHandleReferenceRule),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data ReferenceProfileNestedRules = ReferenceProfileNestedRules-  { required :: ![ReferenceProfileNestedFieldRule],-    recommended :: ![ReferenceProfileNestedFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data ReferenceProfileNestedFieldRule = ReferenceProfileNestedFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data ReferenceProfileFrontmatterRules = ReferenceProfileFrontmatterRules-  { required :: ![ReferenceProfileFieldRule],-    recommended :: ![ReferenceProfileFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data ReferenceProfileSpec = ReferenceProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !ReferenceProfileFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    types :: ![ReferenceProfileTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data ReferenceProfileTypeRule = ReferenceProfileTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !ReferenceProfileFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall ReferenceProfileTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The complete condition-aware descriptor generation, frozen before--- top-level document-reference policies were added.-data ConditionalProfileFieldRule = ConditionalProfileFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat),-    elementFields :: !(Maybe ConditionalProfileNestedRules),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data ConditionalProfileNestedRules = ConditionalProfileNestedRules-  { required :: ![ConditionalProfileNestedFieldRule],-    recommended :: ![ConditionalProfileNestedFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data ConditionalProfileNestedFieldRule = ConditionalProfileNestedFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat),-    when :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data ConditionalProfileFrontmatterRules = ConditionalProfileFrontmatterRules-  { required :: ![ConditionalProfileFieldRule],-    recommended :: ![ConditionalProfileFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data ConditionalProfileSpec = ConditionalProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !ConditionalProfileFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    types :: ![ConditionalProfileTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data ConditionalProfileTypeRule = ConditionalProfileTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !ConditionalProfileFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall ConditionalProfileTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The complete bounded-nested descriptor generation, frozen before--- same-scope field conditions were added. This is the immediately preceding--- public descriptor generation.-data NestedProfileFieldRule = NestedProfileFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat),-    elementFields :: !(Maybe NestedProfileRules)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data NestedProfileRules = NestedProfileRules-  { required :: ![NestedProfileNestedFieldRule],-    recommended :: ![NestedProfileNestedFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data NestedProfileNestedFieldRule = NestedProfileNestedFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data NestedProfileFrontmatterRules = NestedProfileFrontmatterRules-  { required :: ![NestedProfileFieldRule],-    recommended :: ![NestedProfileFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data NestedProfileSpec = NestedProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !NestedProfileFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    types :: ![NestedProfileTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data NestedProfileTypeRule = NestedProfileTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !NestedProfileFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall NestedProfileTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The complete EP-4 field rule, frozen before one-level nested records were--- added. This is the immediately preceding public descriptor generation.-data FormatFieldRule = FormatFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe PreV02FieldFormat)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data FormatFrontmatterRules = FormatFrontmatterRules-  { required :: ![FormatFieldRule],-    recommended :: ![FormatFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data FormatProfileSpec = FormatProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !FormatFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    types :: ![FormatTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data FormatTypeRule = FormatTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !FormatFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall FormatTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The EP-3 field rule, frozen before named formats were added.-data CardinalityFieldRule = CardinalityFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data CardinalityFrontmatterRules = CardinalityFrontmatterRules-  { required :: ![CardinalityFieldRule],-    recommended :: ![CardinalityFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | The complete EP-3 profile shape, frozen before named formats were added.-data CardinalityProfileSpec = CardinalityProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !CardinalityFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    types :: ![CardinalityTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data CardinalityTypeRule = CardinalityTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !CardinalityFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall CardinalityTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The EP-2 field rule, frozen before cardinality was added.-data VocabularyFieldRule = VocabularyFieldRule-  { field :: !Text,-    description :: !(Maybe Text),-    allowedValues :: ![Text]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data VocabularyFrontmatterRules = VocabularyFrontmatterRules-  { required :: ![VocabularyFieldRule],-    recommended :: ![VocabularyFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | The EP-2 profile shape, frozen before cardinality was added.-data VocabularyProfileSpec = VocabularyProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !VocabularyFrontmatterRules,-    allowUnknownTypes :: !Bool,-    allowUnknownFields :: !Bool,-    idField :: !(Maybe Text),-    types :: ![VocabularyTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data VocabularyTypeRule = VocabularyTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !VocabularyFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall VocabularyTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | A field rule from either self-documenting schema generation, before value--- vocabularies were added.-data PreviousFieldRule = PreviousFieldRule-  { field :: !Text,-    description :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data PreviousFrontmatterRules = PreviousFrontmatterRules-  { required :: ![PreviousFieldRule],-    recommended :: ![PreviousFieldRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)---- | The type-aware shape from EP-1, frozen before vocabularies and field-name--- closure were added.-data TypeAwareProfileSpec = TypeAwareProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !PreviousFrontmatterRules,-    allowUnknownTypes :: !Bool,-    idField :: !(Maybe Text),-    types :: ![TypeAwareTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data TypeAwareTypeRule = TypeAwareTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    frontmatter :: !PreviousFrontmatterRules,-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall TypeAwareTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)---- | The self-documenting profile shape published immediately before--- type-specific frontmatter rules. It is frozen as a compatibility decoder in--- exactly the same way as the older 0.2.x shape below.-data DescribedProfileSpec = DescribedProfileSpec-  { name :: !Text,-    description :: !(Maybe Text),-    okfVersion :: !Text,-    frontmatter :: !PreviousFrontmatterRules,-    allowUnknownTypes :: !Bool,-    idField :: !(Maybe Text),-    types :: ![DescribedTypeRule]-  }-  deriving stock (Generic, Eq, Show)-  deriving anyclass (FromDhall)--data DescribedTypeRule = DescribedTypeRule-  { type_ :: !Text,-    description :: !(Maybe Text),-    pathPattern :: !(Maybe Text),-    resourceScheme :: !(Maybe Text),-    requireSchemaSection :: !Bool,-    schemaColumns :: ![Text],-    idPrefix :: !(Maybe Text)-  }-  deriving stock (Generic, Eq, Show)--instance FromDhall DescribedTypeRule where-  autoWith _normalizer =-    genericAutoWith-      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})-    where-      stripTrailingUnderscore fieldName =-        fromMaybe fieldName (Text.stripSuffix "_" fieldName)--emptyFrontmatterRules :: FrontmatterRules-emptyFrontmatterRules = FrontmatterRules {required = [], recommended = [], optional = []}--upgradePreGuidanceCardinality :: PreGuidanceCardinality -> Cardinality-upgradePreGuidanceCardinality = \case-  PreGuidanceAny -> Any-  PreGuidanceScalar -> Scalar-  PreGuidanceList -> List--upgradePreGuidanceFieldFormat :: PreGuidanceFieldFormat -> FieldFormat-upgradePreGuidanceFieldFormat = \case-  PreGuidanceRfc3339Utc -> Rfc3339Utc-  PreGuidanceDate -> Date-  PreGuidanceUri -> Uri-  PreGuidanceUriWithScheme scheme -> UriWithScheme scheme-  PreGuidanceDocumentHandle prefix -> DocumentHandle prefix-  PreGuidanceActor -> Actor-  PreGuidanceHumanActor -> HumanActor-  PreGuidanceInteger -> Integer-  PreGuidanceNonNegativeInteger -> NonNegativeInteger-  PreGuidanceBoolean -> Boolean--upgradePreGuidanceCondition :: PreGuidanceFieldCondition -> FieldCondition-upgradePreGuidanceCondition previous =-  FieldCondition-    { field = previous ^. #field,-      hasValue = previous ^. #hasValue-    }--upgradePreGuidanceHandleRule :: PreGuidanceHandleReferenceRule -> HandleReferenceRule-upgradePreGuidanceHandleRule previous =-  HandleReferenceRule-    { localPrefix = previous ^. #localPrefix,-      externalUriSchemes = previous ^. #externalUriSchemes,-      allowSelf = previous ^. #allowSelf,-      allowLocal = previous ^. #allowLocal,-      externalUriPattern = previous ^. #externalUriPattern-    }--upgradePreGuidancePathRule :: PreGuidancePathReferenceRule -> PathReferenceRule-upgradePreGuidancePathRule previous =-  PathReferenceRule-    { externalUriSchemes = previous ^. #externalUriSchemes,-      allowSelf = previous ^. #allowSelf-    }--upgradePreGuidanceFrontmatter :: PreGuidanceFrontmatterRules -> FrontmatterRules-upgradePreGuidanceFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = map upgradeField (previous ^. #optional)-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = upgradePreGuidanceCardinality (rule ^. #cardinality),-          format = upgradePreGuidanceFieldFormat <$> rule ^. #format,-          elementFields = upgradeNestedRules <$> rule ^. #elementFields,-          objectFields = upgradeNestedRules <$> rule ^. #objectFields,-          reference = upgradePreGuidanceHandleRule <$> rule ^. #reference,-          path = upgradePreGuidancePathRule <$> rule ^. #path,-          when = upgradePreGuidanceCondition <$> rule ^. #when,-          uniqueBy = rule ^. #uniqueBy-        }-    upgradeNestedRules rules =-      NestedRules-        { required = map upgradeNestedField (rules ^. #required),-          recommended = map upgradeNestedField (rules ^. #recommended),-          optional = map upgradeNestedField (rules ^. #optional)-        }-    upgradeNestedField rule =-      NestedFieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = upgradePreGuidanceCardinality (rule ^. #cardinality),-          format = upgradePreGuidanceFieldFormat <$> rule ^. #format,-          path = upgradePreGuidancePathRule <$> rule ^. #path,-          when = upgradePreGuidanceCondition <$> rule ^. #when,-          reference = upgradePreGuidanceHandleRule <$> rule ^. #reference-        }--upgradePreGuidanceTypeRule :: PreGuidanceTypeRule -> TypeRule-upgradePreGuidanceTypeRule rule =-  TypeRule-    { type_ = rule ^. #type_,-      description = rule ^. #description,-      guidance = Nothing,-      frontmatter = upgradePreGuidanceFrontmatter (rule ^. #frontmatter),-      pathPattern = rule ^. #pathPattern,-      resourceScheme = rule ^. #resourceScheme,-      requireSchemaSection = rule ^. #requireSchemaSection,-      schemaColumns = rule ^. #schemaColumns,-      idPrefix = rule ^. #idPrefix-    }--upgradePreGuidanceProfile :: PreGuidanceProfileSpec -> ProfileSpec-upgradePreGuidanceProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradePreGuidanceFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = previous ^. #requireBundleVersion,-      types = map upgradePreGuidanceTypeRule (previous ^. #types)-    }--upgradePreNestedReferenceHandleRule :: PreNestedReferenceHandleReferenceRule -> HandleReferenceRule-upgradePreNestedReferenceHandleRule previous =-  HandleReferenceRule-    { localPrefix = previous ^. #localPrefix,-      externalUriSchemes = previous ^. #externalUriSchemes,-      allowSelf = previous ^. #allowSelf,-      allowLocal = True,-      externalUriPattern = Nothing-    }--upgradePreNestedReferenceFrontmatter :: PreNestedReferenceFrontmatterRules -> FrontmatterRules-upgradePreNestedReferenceFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = map upgradeField (previous ^. #optional)-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = rule ^. #format,-          elementFields = upgradeNestedRules <$> rule ^. #elementFields,-          objectFields = upgradeNestedRules <$> rule ^. #objectFields,-          reference = upgradePreNestedReferenceHandleRule <$> rule ^. #reference,-          path = rule ^. #path,-          when = rule ^. #when,-          uniqueBy = Nothing-        }-    upgradeNestedRules rules =-      NestedRules-        { required = map upgradeNestedField (rules ^. #required),-          recommended = map upgradeNestedField (rules ^. #recommended),-          optional = map upgradeNestedField (rules ^. #optional)-        }-    upgradeNestedField rule =-      NestedFieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = rule ^. #format,-          path = rule ^. #path,-          when = rule ^. #when,-          reference = Nothing-        }--upgradePreNestedReferenceTypeRule :: PreNestedReferenceTypeRule -> TypeRule-upgradePreNestedReferenceTypeRule rule =-  TypeRule-    { type_ = rule ^. #type_,-      description = rule ^. #description,-      guidance = Nothing,-      frontmatter = upgradePreNestedReferenceFrontmatter (rule ^. #frontmatter),-      pathPattern = rule ^. #pathPattern,-      resourceScheme = rule ^. #resourceScheme,-      requireSchemaSection = rule ^. #requireSchemaSection,-      schemaColumns = rule ^. #schemaColumns,-      idPrefix = rule ^. #idPrefix-    }--upgradePreNestedReferenceProfile :: PreNestedReferenceProfileSpec -> ProfileSpec-upgradePreNestedReferenceProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradePreNestedReferenceFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = previous ^. #requireBundleVersion,-      types = map upgradePreNestedReferenceTypeRule (previous ^. #types)-    }--upgradePrePathProfileFrontmatter :: PrePathProfileFrontmatterRules -> FrontmatterRules-upgradePrePathProfileFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = map upgradeField (previous ^. #optional)-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = rule ^. #format,-          elementFields = upgradeNestedRules <$> rule ^. #elementFields,-          objectFields = upgradeNestedRules <$> rule ^. #objectFields,-          reference = upgradePreNestedReferenceHandleRule <$> rule ^. #reference,-          path = Nothing,-          when = rule ^. #when,-          uniqueBy = Nothing-        }-    upgradeNestedRules rules =-      NestedRules-        { required = map upgradeNestedField (rules ^. #required),-          recommended = map upgradeNestedField (rules ^. #recommended),-          optional = map upgradeNestedField (rules ^. #optional)-        }-    upgradeNestedField rule =-      NestedFieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = rule ^. #format,-          path = Nothing,-          when = rule ^. #when,-          reference = Nothing-        }--upgradePreActorProfileFrontmatter :: PreActorProfileFrontmatterRules -> FrontmatterRules-upgradePreActorProfileFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = map upgradeField (previous ^. #optional)-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          elementFields = upgradeNestedRules <$> rule ^. #elementFields,-          objectFields = upgradeNestedRules <$> rule ^. #objectFields,-          reference = upgradePreNestedReferenceHandleRule <$> rule ^. #reference,-          path = Nothing,-          when = rule ^. #when,-          uniqueBy = Nothing-        }-    upgradeNestedRules rules =-      NestedRules-        { required = map upgradeNestedField (rules ^. #required),-          recommended = map upgradeNestedField (rules ^. #recommended),-          optional = map upgradeNestedField (rules ^. #optional)-        }-    upgradeNestedField rule =-      NestedFieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          path = Nothing,-          when = rule ^. #when,-          reference = Nothing-        }--upgradePreObjectProfileFrontmatter :: PreObjectProfileFrontmatterRules -> FrontmatterRules-upgradePreObjectProfileFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = map upgradeField (previous ^. #optional)-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          elementFields = upgradeNestedRules <$> rule ^. #elementFields,-          objectFields = Nothing,-          reference = upgradePreNestedReferenceHandleRule <$> rule ^. #reference,-          path = Nothing,-          when = rule ^. #when,-          uniqueBy = Nothing-        }-    upgradeNestedRules rules =-      NestedRules-        { required = map upgradeNestedField (rules ^. #required),-          recommended = map upgradeNestedField (rules ^. #recommended),-          optional = map upgradeNestedField (rules ^. #optional)-        }-    upgradeNestedField rule =-      NestedFieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          path = Nothing,-          when = rule ^. #when,-          reference = Nothing-        }--upgradeReferenceProfileFrontmatter :: ReferenceProfileFrontmatterRules -> FrontmatterRules-upgradeReferenceProfileFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = []-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          elementFields = upgradeNestedRules <$> rule ^. #elementFields,-          objectFields = Nothing,-          reference = upgradePreNestedReferenceHandleRule <$> rule ^. #reference,-          path = Nothing,-          when = rule ^. #when,-          uniqueBy = Nothing-        }-    upgradeNestedRules rules =-      NestedRules-        { required = map upgradeNestedField (rules ^. #required),-          recommended = map upgradeNestedField (rules ^. #recommended),-          optional = []-        }-    upgradeNestedField rule =-      NestedFieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          path = Nothing,-          when = rule ^. #when,-          reference = Nothing-        }--upgradePreviousFrontmatter :: PreviousFrontmatterRules -> FrontmatterRules-upgradePreviousFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = []-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = [],-          cardinality = Any,-          format = Nothing,-          elementFields = Nothing,-          objectFields = Nothing,-          reference = Nothing,-          path = Nothing,-          when = Nothing,-          uniqueBy = Nothing-        }--upgradeConditionalProfileFrontmatter :: ConditionalProfileFrontmatterRules -> FrontmatterRules-upgradeConditionalProfileFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = []-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          elementFields = upgradeNestedRules <$> rule ^. #elementFields,-          objectFields = Nothing,-          reference = Nothing,-          path = Nothing,-          when = rule ^. #when,-          uniqueBy = Nothing-        }-    upgradeNestedRules rules =-      NestedRules-        { required = map upgradeNestedField (rules ^. #required),-          recommended = map upgradeNestedField (rules ^. #recommended),-          optional = []-        }-    upgradeNestedField rule =-      NestedFieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          path = Nothing,-          when = rule ^. #when,-          reference = Nothing-        }--upgradeNestedProfileFrontmatter :: NestedProfileFrontmatterRules -> FrontmatterRules-upgradeNestedProfileFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = []-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          elementFields = upgradeNestedProfileRules <$> rule ^. #elementFields,-          objectFields = Nothing,-          reference = Nothing,-          path = Nothing,-          when = Nothing,-          uniqueBy = Nothing-        }-    upgradeNestedProfileRules rules =-      NestedRules-        { required = map upgradeNestedField (rules ^. #required),-          recommended = map upgradeNestedField (rules ^. #recommended),-          optional = []-        }-    upgradeNestedField rule =-      NestedFieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          path = Nothing,-          when = Nothing,-          reference = Nothing-        }--upgradeFormatFrontmatter :: FormatFrontmatterRules -> FrontmatterRules-upgradeFormatFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = []-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = upgradePreV02FieldFormat <$> rule ^. #format,-          elementFields = Nothing,-          objectFields = Nothing,-          reference = Nothing,-          path = Nothing,-          when = Nothing,-          uniqueBy = Nothing-        }--upgradeCardinalityFrontmatter :: CardinalityFrontmatterRules -> FrontmatterRules-upgradeCardinalityFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = []-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = rule ^. #cardinality,-          format = Nothing,-          elementFields = Nothing,-          objectFields = Nothing,-          reference = Nothing,-          path = Nothing,-          when = Nothing,-          uniqueBy = Nothing-        }--upgradeVocabularyFrontmatter :: VocabularyFrontmatterRules -> FrontmatterRules-upgradeVocabularyFrontmatter previous =-  FrontmatterRules-    { required = map upgradeField (previous ^. #required),-      recommended = map upgradeField (previous ^. #recommended),-      optional = []-    }-  where-    upgradeField rule =-      FieldRule-        { field = rule ^. #field,-          description = rule ^. #description,-          allowedValues = rule ^. #allowedValues,-          cardinality = Any,-          format = Nothing,-          elementFields = Nothing,-          objectFields = Nothing,-          reference = Nothing,-          path = Nothing,-          when = Nothing,-          uniqueBy = Nothing-        }---- | Lift the generation frozen before @requireBundleVersion@ forward. Its--- contained rule records use the shared 0.7.0.0 frozen types because those--- records later grew too.-upgradePreBundleVersionProfile :: PreBundleVersionProfileSpec -> ProfileSpec-upgradePreBundleVersionProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradePreNestedReferenceFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradePreNestedReferenceTypeRule (previous ^. #types)-    }--upgradePrePathProfile :: PrePathProfileSpec -> ProfileSpec-upgradePrePathProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradePrePathProfileFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (previous ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = upgradePrePathProfileFrontmatter (rule ^. #frontmatter),-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }--upgradePreActorProfile :: PreActorProfileSpec -> ProfileSpec-upgradePreActorProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradePreActorProfileFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (previous ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = upgradePreActorProfileFrontmatter (rule ^. #frontmatter),-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }--upgradePreObjectProfile :: PreObjectProfileSpec -> ProfileSpec-upgradePreObjectProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradePreObjectProfileFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (previous ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = upgradePreObjectProfileFrontmatter (rule ^. #frontmatter),-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }--upgradeReferenceProfile :: ReferenceProfileSpec -> ProfileSpec-upgradeReferenceProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradeReferenceProfileFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (previous ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = upgradeReferenceProfileFrontmatter (rule ^. #frontmatter),-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }--upgradeConditionalProfile :: ConditionalProfileSpec -> ProfileSpec-upgradeConditionalProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradeConditionalProfileFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (previous ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = upgradeConditionalProfileFrontmatter (rule ^. #frontmatter),-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }--upgradeNestedProfile :: NestedProfileSpec -> ProfileSpec-upgradeNestedProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradeNestedProfileFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (previous ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = upgradeNestedProfileFrontmatter (rule ^. #frontmatter),-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }--upgradeFormatProfile :: FormatProfileSpec -> ProfileSpec-upgradeFormatProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradeFormatFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (previous ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = upgradeFormatFrontmatter (rule ^. #frontmatter),-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }--upgradeCardinalityProfile :: CardinalityProfileSpec -> ProfileSpec-upgradeCardinalityProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradeCardinalityFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (previous ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = upgradeCardinalityFrontmatter (rule ^. #frontmatter),-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }--upgradeVocabularyProfile :: VocabularyProfileSpec -> ProfileSpec-upgradeVocabularyProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradeVocabularyFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = previous ^. #allowUnknownFields,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (previous ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = upgradeVocabularyFrontmatter (rule ^. #frontmatter),-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }--upgradeTypeAwareProfile :: TypeAwareProfileSpec -> ProfileSpec-upgradeTypeAwareProfile previous =-  ProfileSpec-    { name = previous ^. #name,-      description = previous ^. #description,-      guidance = Nothing,-      okfVersion = previous ^. #okfVersion,-      frontmatter = upgradePreviousFrontmatter (previous ^. #frontmatter),-      allowUnknownTypes = previous ^. #allowUnknownTypes,-      allowUnknownFields = True,-      idField = previous ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (previous ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = upgradePreviousFrontmatter (rule ^. #frontmatter),-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }--upgradeDescribedProfile :: DescribedProfileSpec -> ProfileSpec-upgradeDescribedProfile described =-  ProfileSpec-    { name = described ^. #name,-      description = described ^. #description,-      guidance = Nothing,-      okfVersion = described ^. #okfVersion,-      frontmatter = upgradePreviousFrontmatter (described ^. #frontmatter),-      allowUnknownTypes = described ^. #allowUnknownTypes,-      allowUnknownFields = True,-      idField = described ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (described ^. #types)-    }-  where-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = rule ^. #description,-          guidance = Nothing,-          frontmatter = emptyFrontmatterRules,-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }---- | Lift a 0.2.x profile into the current shape by attaching neither--- descriptions nor guidance, and by supplying empty type-specific frontmatter.-upgradeLegacyProfile :: LegacyProfileSpec -> ProfileSpec-upgradeLegacyProfile legacy =-  ProfileSpec-    { name = legacy ^. #name,-      description = Nothing,-      guidance = Nothing,-      okfVersion = legacy ^. #okfVersion,-      frontmatter =-        FrontmatterRules-          { required = map undocumented (legacy ^. #frontmatter . #required),-            recommended = map undocumented (legacy ^. #frontmatter . #recommended),-            optional = []-          },-      allowUnknownTypes = legacy ^. #allowUnknownTypes,-      allowUnknownFields = True,-      idField = legacy ^. #idField,-      requireBundleVersion = Nothing,-      types = map upgradeRule (legacy ^. #types)-    }-  where-    undocumented key = FieldRule {field = key, description = Nothing, allowedValues = [], cardinality = Any, format = Nothing, elementFields = Nothing, objectFields = Nothing, reference = Nothing, path = Nothing, when = Nothing, uniqueBy = Nothing}-    upgradeRule rule =-      TypeRule-        { type_ = rule ^. #type_,-          description = Nothing,-          guidance = Nothing,-          frontmatter = emptyFrontmatterRules,-          pathPattern = rule ^. #pathPattern,-          resourceScheme = rule ^. #resourceScheme,-          requireSchemaSection = rule ^. #requireSchemaSection,-          schemaColumns = rule ^. #schemaColumns,-          idPrefix = rule ^. #idPrefix-        }---- | Load and decode a Dhall profile descriptor from a file path. Any evaluation--- or decoding failure is captured as a human-readable 'Left'.------ The pre-guidance shape, pre-nested-reference shape, pre-bundle-version shape,--- pre-path shape, pre-actor shape, pre-object--- shape, reference-aware shape,--- condition-aware shape, bounded-nested shape, EP-4--- format shape, EP-3 cardinality shape, EP-2 vocabulary shape, type-aware EP-1--- shape, self-documenting shape, and okf 0.2.x shape are accepted by frozen--- fallback decoders and upgraded--- with their no-op defaults. When every decoder fails, the /current/ decoder's--- error is reported.-loadProfileFile :: FilePath -> IO (Either Text ProfileSpec)-loadProfileFile path = do-  current <- tryDecode (Dhall.inputFile auto path)-  case current of-    Right spec -> pure (Right spec)-    -- Only the current decoder's error is kept. An author wants to know how-    -- their descriptor differs from today's schema, not from a retired one.-    Left currentError -> maybe (Left currentError) Right <$> firstFrozen frozenDecoders-  where-    -- Newest generation first. Each entry looks identical but is inferred at a-    -- distinct result type, fixed by the upgrade function it names; @auto@ then-    -- picks that generation's decoder. Adding a generation is one line here.-    frozenDecoders :: [IO (Maybe ProfileSpec)]-    frozenDecoders =-      [ attempt upgradePreGuidanceProfile,-        attempt upgradePreNestedReferenceProfile,-        attempt upgradePreBundleVersionProfile,-        attempt upgradePrePathProfile,-        attempt upgradePreActorProfile,-        attempt upgradePreObjectProfile,-        attempt upgradeReferenceProfile,-        attempt upgradeConditionalProfile,-        attempt upgradeNestedProfile,-        attempt upgradeFormatProfile,-        attempt upgradeCardinalityProfile,-        attempt upgradeVocabularyProfile,-        attempt upgradeTypeAwareProfile,-        attempt upgradeDescribedProfile,-        attempt upgradeLegacyProfile-      ]--    -- Short-circuiting, so a descriptor that decodes at the first frozen-    -- generation costs one extra parse rather than thirteen.-    firstFrozen :: [IO (Maybe ProfileSpec)] -> IO (Maybe ProfileSpec)-    firstFrozen [] = pure Nothing-    firstFrozen (decoder : remaining) =-      decoder >>= \case-        Just spec -> pure (Just spec)-        Nothing -> firstFrozen remaining--    attempt :: (FromDhall a) => (a -> ProfileSpec) -> IO (Maybe ProfileSpec)-    attempt upgrade = either (const Nothing) (Just . upgrade) <$> tryDecode (Dhall.inputFile auto path)--    tryDecode :: IO a -> IO (Either Text a)-    tryDecode action =-      (Right <$> action)-        `catch` \(exception :: SomeException) -> pure (Left (Text.pack (show exception)))---- | Does an already-evaluated Dhall expression decode as a profile? Tries the--- current schema, then the pre-guidance, pre-nested-reference,--- pre-bundle-version, pre-path, pre-actor, pre-object,--- reference-aware,--- condition-aware, bounded-nested, EP-4, EP-3, EP-2, EP-1, self-documenting, and--- okf 0.2.x schemas, so the published @okf-profiles@ package still enumerates.--- Uses 'Dhall.rawInput', which normalizes and runs the decoder's extractor--- without throwing, which is what lets registry enumeration be pure.-decodeProfileExpr :: Expr Src Void -> Maybe ProfileSpec-decodeProfileExpr expression =-  Dhall.rawInput Dhall.auto expression-    <|> fmap upgradePreGuidanceProfile (Dhall.rawInput Dhall.auto expression)-    <|> decodeProfilesBeforeGuidance expression---- | The generic Dhall record extractor deliberately ignores extra record--- members. Without this guard, a value from the 0.8.0.0 generation can fall--- through to an older decoder and silently lose nested-reference or uniqueness--- declarations. Every non-empty 0.8.0.0 field-rule value carries at least one--- of these post-0.7 record members, even when its value is @None@.-decodeProfilesBeforeGuidance :: Expr Src Void -> Maybe ProfileSpec-decodeProfilesBeforeGuidance expression-  | containsPost07DescriptorField expression = Nothing-  | otherwise =-      fmap upgradePreNestedReferenceProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradePreBundleVersionProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradePrePathProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradePreActorProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradePreObjectProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradeReferenceProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradeConditionalProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradeNestedProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradeFormatProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradeCardinalityProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradeVocabularyProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradeTypeAwareProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradeDescribedProfile (Dhall.rawInput Dhall.auto expression)-        <|> fmap upgradeLegacyProfile (Dhall.rawInput Dhall.auto expression)--containsPost07DescriptorField :: Expr Src Void -> Bool-containsPost07DescriptorField =-  anyOf (cosmosOf Dhall.Core.subExpressions) $ \case-    Dhall.Core.RecordLit fields ->-      any (`Dhall.Map.member` fields) ["uniqueBy", "allowLocal", "externalUriPattern"]-    _ -> False---- | The description a profile attaches to a frontmatter key, looking in--- @required@ first, then @recommended@, then @optional@. 'Nothing' when the key--- is undocumented or absent from the profile entirely.-profileFieldDescription :: ProfileSpec -> Text -> Maybe Text-profileFieldDescription spec key =-  case [rule | rule <- rules, rule ^. #field == key] of-    (rule : _) -> rule ^. #description-    [] -> Nothing-  where-    rules =-      spec ^. #frontmatter . #required-        <> spec ^. #frontmatter . #recommended-        <> spec ^. #frontmatter . #optional---- | A malformed profile definition. The optional type is absent for profile--- scope and present for a type-specific scope. The list name is @required@,--- @recommended@, or @optional@.-data ProfileDefinitionError-  = DuplicateTypeRule Text-  | DuplicateFieldRule (Maybe Text) Text Text-  | ConflictingFieldRequirement (Maybe Text) Text-  | UnsatisfiableVocabulary (Maybe Text) Text [Text] [Text]-  | ConflictingCardinality (Maybe Text) Text Cardinality Cardinality-  | ElementFieldsRequireList (Maybe Text) FieldPath Cardinality-  | InvalidFormatParameter FieldPath FieldFormat Text-  | ConflictingFieldFormat FieldPath FieldFormat FieldFormat-  | EmptyConditionValues (Maybe Text) FieldPath FieldPath-  | ConditionFieldNotDeclared (Maybe Text) FieldPath FieldPath-  | ConditionFieldNotScalar (Maybe Text) FieldPath FieldPath Cardinality-  | ConditionFieldOpenVocabulary (Maybe Text) FieldPath FieldPath-  | ConditionFieldHasUnreachableValues (Maybe Text) FieldPath FieldPath [Text] [Text]-  | SelfConditionalField (Maybe Text) FieldPath-  | InvalidReferencePrefix (Maybe Text) FieldPath Text-  | ReferencePrefixNotDeclared (Maybe Text) FieldPath Text-  | ReferenceRequiresIdField (Maybe Text) FieldPath-  | InvalidExternalReferenceScheme (Maybe Text) FieldPath Text-  | ConflictingReferencePrefix Text FieldPath Text Text-  | ReferenceWithFormat (Maybe Text) FieldPath FieldFormat-  | -- | an @optional@ rule carries a @when@ condition, which gates only presence-    -- and is therefore dead: an optional rule has no presence check at all-    OptionalFieldWithCondition (Maybe Text) FieldPath-  | -- | a rule declares @objectFields@ alongside an explicit scalar or list-    -- cardinality; an object is neither, so the pairing cannot be satisfied-    ObjectFieldsRequireObjectShape (Maybe Text) FieldPath Cardinality-  | -- | one rule declares both a document-handle policy and a path policy;-    -- a value cannot be resolved as both a handle and a path-    PathReferenceWithHandleReference (Maybe Text) FieldPath-  | InvalidExternalUriPattern (Maybe Text) FieldPath Text Text-  | ConflictingExternalUriPatterns Text FieldPath Text Text-  | UniqueByRequiresElementFields (Maybe Text) FieldPath Text-  | UniqueByFieldNotDeclared (Maybe Text) FieldPath-  | UniqueByFieldNotUnconditionallyRequired (Maybe Text) FieldPath-  | UniqueByFieldNotScalar (Maybe Text) FieldPath Cardinality-  | ConflictingUniqueBy Text FieldPath Text Text-  | -- | @okfVersion@ is not @\<major\>.\<minor\>@-    InvalidProfileOkfVersion Text-  | -- | @okfVersion@ names a major version okf does not implement, so okf cannot-    -- know which of its rules still hold-    ProfileOkfVersionNotUnderstood Text-  | -- | @requireBundleVersion@ is not @\<major\>.\<minor\>@, so no bundle-    -- declaration could ever be compared against it-    InvalidRequiredBundleVersion Text-  | -- | a required or recommended rule names a key the declared version-    -- supersedes (scope, path, declared version, version that superseded the key)-    FieldSupersededInOkfVersion (Maybe Text) FieldPath Text Text-  | -- | a rule names a value format introduced after the declared version-    -- (scope, path, format, declared version, version that introduced the format)-    FormatRequiresOkfVersion (Maybe Text) FieldPath FieldFormat Text Text-  deriving stock (Generic, Eq, Ord, Show)---- | Whether a 'PresenceClause' demands a key or merely recommends it. There is--- deliberately no @OptionalField@ constructor: an optional key is encoded as an--- 'EffectiveFieldRule' with /no/ presence clauses at all.-data FieldRequirement = RecommendedField | RequiredField-  deriving stock (Generic, Eq, Ord, Show)---- | One reason a key may have to be present, optionally gated by a condition on--- another same-scope key. Abstract: read it with 'presenceClauseRequirement' and--- 'presenceClauseCondition'.-data PresenceClause = PresenceClause-  { requirement :: !FieldRequirement,-    condition :: !(Maybe FieldCondition)-  }-  deriving stock (Generic, Eq, Show)---- | Everything that actually applies to one frontmatter key for one concept--- type: the profile-scope declaration merged with the type-scope one per--- [ADR 5](docs/adr/5-compile-profile-rules-before-validation.md). Abstract: read--- it with the @fieldRule*@ accessors below, never by pattern matching, so that--- later profile features can extend it without breaking consumers.-data EffectiveFieldRule = EffectiveFieldRule-  { presenceClauses :: ![PresenceClause],-    description :: !(Maybe Text),-    allowedValues :: ![Text],-    cardinality :: !Cardinality,-    format :: !(Maybe FieldFormat),-    elementFields :: !(Maybe (Map Text EffectiveFieldRule)),-    objectFields :: !(Maybe (Map Text EffectiveFieldRule)),-    reference :: !(Maybe HandleReferenceRule),-    path :: !(Maybe PathReferenceRule),-    uniqueBy :: !(Maybe Text),-    compiledExternalUriPattern :: !(Maybe Regex)-  }-  deriving stock (Generic)--instance Eq EffectiveFieldRule where-  left == right =-    left ^. #presenceClauses == right ^. #presenceClauses-      && left ^. #description == right ^. #description-      && left ^. #allowedValues == right ^. #allowedValues-      && left ^. #cardinality == right ^. #cardinality-      && left ^. #format == right ^. #format-      && left ^. #elementFields == right ^. #elementFields-      && left ^. #objectFields == right ^. #objectFields-      && left ^. #reference == right ^. #reference-      && left ^. #path == right ^. #path-      && left ^. #uniqueBy == right ^. #uniqueBy--instance Show EffectiveFieldRule where-  show rule =-    "EffectiveFieldRule "-      <> show-        ( rule ^. #presenceClauses,-          rule ^. #description,-          rule ^. #allowedValues,-          rule ^. #cardinality,-          rule ^. #format,-          rule ^. #elementFields,-          rule ^. #objectFields,-          rule ^. #reference,-          rule ^. #path,-          rule ^. #uniqueBy-        )---- | The stable lowercase display name for a cardinality: @any@, @scalar@,--- @list@, or @object@. These are the names the CLI prints and the names--- generated profile documentation uses, so a reader who has seen one recognizes--- the other. @object@ is also the word the CLI already prints for an actual--- mapping value, so a cardinality-mismatch message reads coherently.-renderCardinalityName :: Cardinality -> Text-renderCardinalityName = \case-  Any -> "any"-  Scalar -> "scalar"-  List -> "list"-  Object -> "object"---- | The stable display name for a named format: @rfc3339-utc@, @date@, @uri@,--- @uri-with-scheme(SCHEME)@, @document-handle(PREFIX)@, @actor@,--- @human-actor@, @integer@, @non-negative-integer@, or @boolean@. As with--- 'renderCardinalityName', this vocabulary is shared between the CLI and--- generated documentation and must not drift between them.-renderFieldFormatName :: FieldFormat -> Text-renderFieldFormatName = \case-  Rfc3339Utc -> "rfc3339-utc"-  Date -> "date"-  Uri -> "uri"-  UriWithScheme scheme -> "uri-with-scheme(" <> scheme <> ")"-  DocumentHandle prefix -> "document-handle(" <> prefix <> ")"-  Actor -> "actor"-  HumanActor -> "human-actor"-  Integer -> "integer"-  NonNegativeInteger -> "non-negative-integer"-  Boolean -> "boolean"---- | The presence clauses that govern whether this key must be present, in the--- order the profile declared them. An __empty list means the key is optional__:--- it is fully validated whenever it is present and never reported when absent,--- in any validation mode. A clause with 'RequiredField' is always checked; a--- clause with 'RecommendedField' is checked only under--- 'Okf.Validation.StrictAuthoring'. A clause carrying a 'FieldCondition' applies--- only when that condition holds for the document being checked.-fieldRulePresenceClauses :: EffectiveFieldRule -> [PresenceClause]-fieldRulePresenceClauses rule = rule ^. #presenceClauses---- | Prose documenting the key, merged across profile and type scope with--- type-level prose winning. Purely documentary: it is never checked against a--- document and can never produce a 'ProfileViolation'.-fieldRuleDescription :: EffectiveFieldRule -> Maybe Text-fieldRuleDescription rule = rule ^. #description---- | The closed vocabulary of permitted textual values. An __empty list means--- unconstrained__, not "no value is permitted".-fieldRuleAllowedValues :: EffectiveFieldRule -> [Text]-fieldRuleAllowedValues rule = rule ^. #allowedValues---- | Whether the key must be a single value, a non-empty list, or either.-fieldRuleCardinality :: EffectiveFieldRule -> Cardinality-fieldRuleCardinality rule = rule ^. #cardinality---- | The named textual format constraining present values, if any.-fieldRuleFormat :: EffectiveFieldRule -> Maybe FieldFormat-fieldRuleFormat rule = rule ^. #format---- | The document-reference policy for this key, if any.-fieldRuleReference :: EffectiveFieldRule -> Maybe HandleReferenceRule-fieldRuleReference rule = rule ^. #reference---- | The required scalar member whose values must be unique within this one--- list of records, or 'Nothing' when no list-local key is declared.-fieldRuleUniqueBy :: EffectiveFieldRule -> Maybe Text-fieldRuleUniqueBy rule = rule ^. #uniqueBy---- | The path-valued policy for this key, if any. Distinct from--- 'fieldRuleReference': a handle resolves against the bundle's document-ID--- index, a path against its concept tree. A rule never carries both — compiling--- one that does is a 'PathReferenceWithHandleReference' definition error — so a--- consumer can read whichever is present without disambiguating.------ Unlike 'fieldRuleReference' this can be present on a rule taken from--- 'fieldRuleElementFields' or 'fieldRuleObjectFields', because--- @sources[].resource@ is the field the policy exists for.-fieldRulePath :: EffectiveFieldRule -> Maybe PathReferenceRule-fieldRulePath rule = rule ^. #path---- | Rules for the flat object stored in each element of a list-valued key,--- keyed by nested key name, or 'Nothing' when the key declares no nested shape.--- Nested rules are depth-bounded: a nested rule never itself has element fields,--- so 'fieldRuleElementFields' on a value taken from this map is always--- 'Nothing'.-fieldRuleElementFields :: EffectiveFieldRule -> Maybe (Map Text EffectiveFieldRule)-fieldRuleElementFields rule = rule ^. #elementFields---- | Rules for the members of the mapping stored at this key, keyed by member--- name, or 'Nothing' when the key declares no object shape. Like--- 'fieldRuleElementFields' this is depth-bounded: a value taken from this map--- always has 'Nothing' for both nested accessors. A rule may declare both, which--- means either spelling of the value is accepted and both are checked against--- the same member rules.-fieldRuleObjectFields :: EffectiveFieldRule -> Maybe (Map Text EffectiveFieldRule)-fieldRuleObjectFields rule = rule ^. #objectFields---- | Whether this clause demands the key or merely recommends it.-presenceClauseRequirement :: PresenceClause -> FieldRequirement-presenceClauseRequirement clause = clause ^. #requirement---- | The same-scope predicate gating this clause, or 'Nothing' when it always--- applies.-presenceClauseCondition :: PresenceClause -> Maybe FieldCondition-presenceClauseCondition clause = clause ^. #condition---- | A raw profile whose authoring contradictions have been rejected and whose--- effective profile-plus-type frontmatter rules have been precomputed.-data CompiledProfile = CompiledProfile-  { spec :: !ProfileSpec,-    baseRules :: !(Map Text EffectiveFieldRule),-    rulesByType :: !(Map Text (Map Text EffectiveFieldRule)),-    -- | @requireBundleVersion@ already parsed, so 'validateProfileVersion' never-    -- re-parses and cannot disagree with what compilation accepted.-    requiredBundleVersion :: !(Maybe OkfVersion)-  }-  deriving stock (Generic, Eq, Show)--compiledProfileSpec :: CompiledProfile -> ProfileSpec-compiledProfileSpec compiled = compiled ^. #spec---- | The minimum OKF version the profile requires its bundle to declare, already--- parsed. 'Nothing' when the profile requires nothing, which is the default and--- the case for almost every profile.-compiledProfileRequiredBundleVersion :: CompiledProfile -> Maybe OkfVersion-compiledProfileRequiredBundleVersion compiled = compiled ^. #requiredBundleVersion---- | The concept @type@ strings the profile declares, in the order the descriptor--- declares them. Declaration order is the author's and is preserved because--- documentation and display should follow it rather than an alphabetical--- reordering.-compiledProfileTypeNames :: CompiledProfile -> [Text]-compiledProfileTypeNames compiled =-  [rule ^. #type_ | rule <- compiledProfileSpec compiled ^. #types]---- | The rules that apply to every document, whatever its type, keyed by--- frontmatter key name.-compiledProfileBaseRules :: CompiledProfile -> Map Text EffectiveFieldRule-compiledProfileBaseRules compiled = compiled ^. #baseRules---- | The rules that apply to a document of the given @type@: the profile-scope--- rules merged with that type's own. A type the profile does not declare falls--- back to the profile-scope rules alone, because a profile with--- @allowUnknownTypes = True@ still applies its profile-wide expectations to a--- document whose type it does not recognize.-compiledProfileRulesForType :: CompiledProfile -> Text -> Map Text EffectiveFieldRule-compiledProfileRulesForType = effectiveRulesForType--compileProfile :: ProfileSpec -> Either (NonEmpty ProfileDefinitionError) CompiledProfile-compileProfile rawSpec =-  case definitionErrors of-    firstError : remainingErrors -> Left (firstError :| remainingErrors)-    [] ->-      Right-        CompiledProfile-          { spec = rawSpec,-            baseRules,-            rulesByType =-              Map.fromList-                [ (rule ^. #type_, mergeRules baseRules (compileRules (rule ^. #frontmatter)))-                | rule <- rawSpec ^. #types-                ],-            -- Safe here and only here: 'requiredBundleVersionErrors' is one of-            -- the checks 'definitionErrors' collects, so reaching this branch-            -- means the value parsed.-            requiredBundleVersion = rawSpec ^. #requireBundleVersion >>= parseOkfVersion-          }-  where-    baseRules = compileRules (rawSpec ^. #frontmatter)-    typeNames = map (^. #type_) (rawSpec ^. #types)-    definitionErrors =-      List.sortOn definitionErrorKey $-        map DuplicateTypeRule (duplicates typeNames)-          <> scopeErrors Nothing (rawSpec ^. #frontmatter)-          <> concat-            [ scopeErrors (Just (rule ^. #type_)) (rule ^. #frontmatter)-            | rule <- rawSpec ^. #types-            ]-          <> vocabularyErrors-          <> cardinalityErrors-          <> nestedCardinalityErrors-          <> objectCardinalityErrors-          <> formatParameterErrors-          <> conflictingFormatErrors-          <> conditionDefinitionErrors-          <> referenceDefinitionErrors-          <> uniquenessDefinitionErrors-          <> versionErrors-          <> requiredBundleVersionErrors--    definitionErrorKey = \case-      DuplicateTypeRule ctype -> (1 :: Int, ctype, 0 :: Int, "", 0 :: Int)-      DuplicateFieldRule scope listName key ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, listKey listName, key, 0)-      ConflictingFieldRequirement scope key ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, 2, key, 0)-      UnsatisfiableVocabulary scope key _ _ ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, 3, key, 0)-      ConflictingCardinality scope key _ _ ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, 4, key, 0)-      ElementFieldsRequireList scope path cardinality ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, 4, renderFieldPathKey path, fromEnum (cardinality == Scalar))-      InvalidFormatParameter path fieldFormat parameter ->-        (2, renderFieldPathKey path, 5, Text.pack (show fieldFormat), Text.length parameter)-      ConflictingFieldFormat path profileFormat typeFormat ->-        (2, renderFieldPathKey path, 6, Text.pack (show profileFormat), fromEnum (profileFormat == typeFormat))-      EmptyConditionValues scope target source -> conditionErrorKey scope target source 7-      ConditionFieldNotDeclared scope target source -> conditionErrorKey scope target source 8-      ConditionFieldNotScalar scope target source cardinality ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, 9, renderFieldPathKey target <> ":" <> renderFieldPathKey source, fromEnum (cardinality == Scalar))-      ConditionFieldOpenVocabulary scope target source -> conditionErrorKey scope target source 10-      ConditionFieldHasUnreachableValues scope target source _ _ -> conditionErrorKey scope target source 11-      SelfConditionalField scope target ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, 12, renderFieldPathKey target, 0)-      InvalidReferencePrefix scope target prefix -> referenceErrorKey scope target 13 prefix-      ReferencePrefixNotDeclared scope target prefix -> referenceErrorKey scope target 14 prefix-      ReferenceRequiresIdField scope target -> referenceErrorKey scope target 15 ""-      InvalidExternalReferenceScheme scope target scheme -> referenceErrorKey scope target 16 scheme-      ConflictingReferencePrefix ctype target profilePrefix typePrefix ->-        (1, ctype, 17, renderFieldPathKey target <> ":" <> profilePrefix, Text.length typePrefix)-      ReferenceWithFormat scope target fieldFormat -> referenceErrorKey scope target 18 (Text.pack (show fieldFormat))-      OptionalFieldWithCondition scope target ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, 19, renderFieldPathKey target, 0)-      ObjectFieldsRequireObjectShape scope fieldPath cardinality ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, 20, renderFieldPathKey fieldPath, fromEnum (cardinality == Scalar))-      PathReferenceWithHandleReference scope target -> referenceErrorKey scope target 21 ""-      InvalidExternalUriPattern scope target patternText detail ->-        referenceErrorKey scope target 22 (patternText <> ":" <> detail)-      ConflictingExternalUriPatterns ctype target profilePattern typePattern ->-        (1, ctype, 23, renderFieldPathKey target <> ":" <> profilePattern, Text.length typePattern)-      UniqueByRequiresElementFields scope target key -> uniqueErrorKey scope target 24 key-      UniqueByFieldNotDeclared scope target -> uniqueErrorKey scope target 25 ""-      UniqueByFieldNotUnconditionallyRequired scope target -> uniqueErrorKey scope target 26 ""-      UniqueByFieldNotScalar scope target cardinality -> uniqueErrorKey scope target 27 (Text.pack (show cardinality))-      ConflictingUniqueBy ctype target profileKey typeKey ->-        (1, ctype, 28, renderFieldPathKey target <> ":" <> profileKey, Text.length typeKey)-      -- The two version-parse errors are profile-wide rather than scoped, and-      -- rank below every scope rank: if the declared version is unreadable, every-      -- version-derived error below is downstream noise and the reader should see-      -- the cause first. Nothing constrains the first component to be-      -- non-negative.-      InvalidProfileOkfVersion rawVersion -> (-1, rawVersion, 0, "", 0)-      ProfileOkfVersionNotUnderstood rawVersion -> (-1, rawVersion, 1, "", 0)-      InvalidRequiredBundleVersion rawVersion -> (-1, rawVersion, 2, "", 0)-      FieldSupersededInOkfVersion scope path _declared supersededIn ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, 30, renderFieldPathKey path <> ":" <> supersededIn, 0)-      FormatRequiresOkfVersion scope path fieldFormat _declared introducedIn ->-        let (scopeRank, typeName) = scopeKey scope-         in (scopeRank, typeName, 31, renderFieldPathKey path <> ":" <> introducedIn, Text.length (Text.pack (show fieldFormat)))--    scopeKey Nothing = (0, "")-    scopeKey (Just ctype) = (1, ctype)-    listKey "required" = 0-    listKey _ = 1-    conditionErrorKey scope target source rank =-      let (scopeRank, typeName) = scopeKey scope-       in (scopeRank, typeName, rank, renderFieldPathKey target <> ":" <> renderFieldPathKey source, 0)-    referenceErrorKey scope target rank detail =-      let (scopeRank, typeName) = scopeKey scope-       in (scopeRank, typeName, rank, renderFieldPathKey target <> ":" <> detail, 0)-    uniqueErrorKey = referenceErrorKey--    scopeErrors scope FrontmatterRules {required, recommended, optional} =-      [DuplicateFieldRule scope "required" key | key <- duplicates (map (^. #field) required)]-        <> [DuplicateFieldRule scope "recommended" key | key <- duplicates (map (^. #field) recommended)]-        <> [DuplicateFieldRule scope "optional" key | key <- duplicates (map (^. #field) optional)]-        <> [ ConflictingFieldRequirement scope key-           | key <- presenceListCollisions (map (^. #field) required) (map (^. #field) recommended) (map (^. #field) optional)-           ]-        <> concatMap (nestedScopeErrors scope) (required <> recommended <> optional)--    nestedScopeErrors scope parentRule =-      concatMap oneNestedRuleSet (declaredNestedRuleSets parentRule)-      where-        oneNestedRuleSet NestedRules {required, recommended, optional} =-          let qualify key = parentRule ^. #field <> "." <> key-           in [DuplicateFieldRule scope "nested required" (qualify key) | key <- duplicates (map (^. #field) required)]-                <> [DuplicateFieldRule scope "nested recommended" (qualify key) | key <- duplicates (map (^. #field) recommended)]-                <> [DuplicateFieldRule scope "nested optional" (qualify key) | key <- duplicates (map (^. #field) optional)]-                <> [ ConflictingFieldRequirement scope (qualify key)-                   | key <- presenceListCollisions (map (^. #field) required) (map (^. #field) recommended) (map (^. #field) optional)-                   ]--    -- One key classified by more than one presence list at a single scope. The-    -- profile cannot say both "always check for this" and "never check for-    -- this", so any pairing is a definition error rather than a precedence rule.-    presenceListCollisions requiredKeys recommendedKeys optionalKeys =-      List.nub . List.sort . concat $-        [ List.intersect requiredKeys recommendedKeys,-          List.intersect requiredKeys optionalKeys,-          List.intersect recommendedKeys optionalKeys-        ]--    duplicates = mapMaybe duplicateHead . List.group . List.sort-    duplicateHead (candidate : _ : _) = Just candidate-    duplicateHead _ = Nothing--    vocabularyErrors =-      [ UnsatisfiableVocabulary (Just (rule ^. #type_)) key profileValues typeValues-      | rule <- rawSpec ^. #types,-        let typeRules = compileRules (rule ^. #frontmatter),-        (key, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),-        let profileValues = profileRule ^. #allowedValues-            typeValues = typeRule ^. #allowedValues,-        not (null profileValues),-        not (null typeValues),-        null (mergeVocabulary profileValues typeValues)-      ]-        <> [ UnsatisfiableVocabulary (Just (rule ^. #type_)) (parentKey <> "." <> nestedKey) profileValues typeValues-           | rule <- rawSpec ^. #types,-             let typeRules = compileRules (rule ^. #frontmatter),-             (parentKey, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),-             (profileNested, typeNested) <- pairedNestedRuleMaps profileRule typeRule,-             (nestedKey, (profileNestedRule, typeNestedRule)) <- Map.toAscList (Map.intersectionWith (,) profileNested typeNested),-             let profileValues = profileNestedRule ^. #allowedValues-                 typeValues = typeNestedRule ^. #allowedValues,-             not (null profileValues),-             not (null typeValues),-             null (mergeVocabulary profileValues typeValues)-           ]--    cardinalityErrors =-      [ ConflictingCardinality (Just (rule ^. #type_)) key profileCardinality typeCardinality-      | rule <- rawSpec ^. #types,-        let typeRules = compileRules (rule ^. #frontmatter),-        (key, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),-        let profileCardinality = profileRule ^. #cardinality-            typeCardinality = typeRule ^. #cardinality,-        profileCardinality /= Any,-        typeCardinality /= Any,-        profileCardinality /= typeCardinality-      ]-        <> [ ConflictingCardinality (Just (rule ^. #type_)) (parentKey <> "." <> nestedKey) profileCardinality typeCardinality-           | rule <- rawSpec ^. #types,-             let typeRules = compileRules (rule ^. #frontmatter),-             (parentKey, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),-             (profileNested, typeNested) <- pairedNestedRuleMaps profileRule typeRule,-             (nestedKey, (profileNestedRule, typeNestedRule)) <- Map.toAscList (Map.intersectionWith (,) profileNested typeNested),-             let profileCardinality = profileNestedRule ^. #cardinality-                 typeCardinality = typeNestedRule ^. #cardinality,-             profileCardinality /= Any,-             typeCardinality /= Any,-             profileCardinality /= typeCardinality-           ]--    nestedCardinalityErrors =-      [ ElementFieldsRequireList scope (topLevelFieldPath (fieldRule ^. #field)) Scalar-      | (scope, rules) <- scopedFrontmatterRules,-        fieldRule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,-        isJust (fieldRule ^. #elementFields),-        fieldRule ^. #cardinality == Scalar-      ]--    -- The mirror image: @objectFields@ says the value is a mapping, and neither-    -- an explicit @scalar@ nor an explicit @list@ can be one.-    objectCardinalityErrors =-      [ ObjectFieldsRequireObjectShape scope (topLevelFieldPath (fieldRule ^. #field)) declared-      | (scope, rules) <- scopedFrontmatterRules,-        fieldRule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,-        isJust (fieldRule ^. #objectFields),-        let declared = fieldRule ^. #cardinality,-        declared == Scalar || declared == List-      ]--    scopedFrontmatterRules =-      (Nothing, rawSpec ^. #frontmatter)-        : [(Just (rule ^. #type_), rule ^. #frontmatter) | rule <- rawSpec ^. #types]--    -- The nested rule sets one raw rule declares: its list-element rules, its-    -- object-member rules, or both. Deduplicated because @mk.recordOrList@-    -- deliberately declares the same rules under both names, and a definition-    -- error names a path such as @verified.by@ that does not distinguish the two-    -- — so without this the same incoherence would be reported twice.-    declaredNestedRuleSets rawRule =-      List.nub (catMaybes [rawRule ^. #elementFields, rawRule ^. #objectFields])--    -- The same idea across two scopes: the nested maps a profile-scope rule and-    -- a type-scope rule both declare, paired shape with matching shape. Pairing-    -- an element map against an object map would compare rules that never meet.-    pairedNestedRuleMaps profileRule typeRule =-      List.nub-        [ (profileNested, typeNested)-        | nestedMap <- [(^. #elementFields), (^. #objectFields)],-          Just profileNested <- [nestedMap profileRule],-          Just typeNested <- [nestedMap typeRule]-        ]--    formatParameterErrors =-      [ InvalidFormatParameter (topLevelFieldPath (rule ^. #field)) fieldFormat parameter-      | rules <- (rawSpec ^. #frontmatter) : map (^. #frontmatter) (rawSpec ^. #types),-        rule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,-        Just (fieldFormat, parameter) <- [invalidFormatParameter =<< rule ^. #format]-      ]-        <> [ InvalidFormatParameter (nestedDefinitionPath (rule ^. #field) (nestedRule ^. #field)) fieldFormat parameter-           | rules <- (rawSpec ^. #frontmatter) : map (^. #frontmatter) (rawSpec ^. #types),-             rule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,-             nestedRules <- declaredNestedRuleSets rule,-             nestedRule <- nestedRules ^. #required <> nestedRules ^. #recommended <> nestedRules ^. #optional,-             Just (fieldFormat, parameter) <- [invalidFormatParameter =<< nestedRule ^. #format]-           ]--    conflictingFormatErrors =-      [ ConflictingFieldFormat (topLevelFieldPath key) profileFormat typeFormat-      | rule <- rawSpec ^. #types,-        let typeRules = compileRules (rule ^. #frontmatter),-        (key, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),-        Just profileFormat <- [profileRule ^. #format],-        Just typeFormat <- [typeRule ^. #format],-        mergeFieldFormat (Just profileFormat) (Just typeFormat) == Nothing-      ]-        <> [ ConflictingFieldFormat (nestedDefinitionPath parentKey nestedKey) profileFormat typeFormat-           | rule <- rawSpec ^. #types,-             let typeRules = compileRules (rule ^. #frontmatter),-             (parentKey, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),-             (profileNested, typeNested) <- pairedNestedRuleMaps profileRule typeRule,-             (nestedKey, (profileNestedRule, typeNestedRule)) <- Map.toAscList (Map.intersectionWith (,) profileNested typeNested),-             Just profileFormat <- [profileNestedRule ^. #format],-             Just typeFormat <- [typeNestedRule ^. #format],-             mergeFieldFormat (Just profileFormat) (Just typeFormat) == Nothing-           ]--    conditionDefinitionErrors =-      conditionErrors Nothing Nothing (rawSpec ^. #frontmatter) baseRules-        <> concat-          [ let typeRules = compileRules (rule ^. #frontmatter)-                mergedRules = mergeRules baseRules typeRules-             in conditionErrors (Just (rule ^. #type_)) Nothing (rule ^. #frontmatter) mergedRules-          | rule <- rawSpec ^. #types-          ]--    conditionErrors scope parent rules effectiveRules =-      concatMap (fieldConditionErrors scope parent effectiveRules) (rules ^. #required <> rules ^. #recommended)-        <> [ deadCondition scope parent (rawRule ^. #field)-           | rawRule <- rules ^. #optional,-             isJust (rawRule ^. #when)-           ]-        <> List.nub-          ( concat-              [ concatMap-                  (fieldConditionErrors scope (Just (rawRule ^. #field)) effectiveNestedRules)-                  (nestedRules ^. #required <> nestedRules ^. #recommended)-                  <> [ deadCondition scope (Just (rawRule ^. #field)) (nestedRule ^. #field)-                     | nestedRule <- nestedRules ^. #optional,-                       isJust (nestedRule ^. #when)-                     ]-              | rawRule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,-                let effectiveRule = Map.lookup (rawRule ^. #field) effectiveRules,-                (nestedRules, effectiveNestedRules) <--                  catMaybes-                    [ (,) <$> (rawRule ^. #elementFields) <*> (effectiveRule >>= (^. #elementFields)),-                      (,) <$> (rawRule ^. #objectFields) <*> (effectiveRule >>= (^. #objectFields))-                    ]-              ]-          )--    -- A condition gates presence, and an optional rule has no presence clause to-    -- gate, so the pairing is dead in the descriptor rather than a weaker rule.-    deadCondition scope parent key =-      OptionalFieldWithCondition-        scope-        (maybe (topLevelFieldPath key) (\parentKey -> nestedDefinitionPath parentKey key) parent)--    fieldConditionErrors scope parent effectiveRules rawRule =-      case rawRule ^. #when of-        Nothing -> []-        Just FieldCondition {field = sourceKey, hasValue = conditionValues} ->-          let targetKey = rawRule ^. #field-              targetPath = maybe (topLevelFieldPath targetKey) (\parentKey -> nestedDefinitionPath parentKey targetKey) parent-              sourcePath = maybe (topLevelFieldPath sourceKey) (\parentKey -> nestedDefinitionPath parentKey sourceKey) parent-              normalizedValues = deduplicate conditionValues-              sourceErrors =-                case Map.lookup sourceKey effectiveRules of-                  Nothing -> [ConditionFieldNotDeclared scope targetPath sourcePath]-                  Just sourceRule ->-                    [ ConditionFieldNotScalar scope targetPath sourcePath (sourceRule ^. #cardinality)-                    | sourceRule ^. #cardinality /= Scalar-                    ]-                      <> [ ConditionFieldOpenVocabulary scope targetPath sourcePath-                         | null (sourceRule ^. #allowedValues)-                         ]-                      <> let unreachable = filter (`notElem` sourceRule ^. #allowedValues) normalizedValues-                          in [ ConditionFieldHasUnreachableValues scope targetPath sourcePath unreachable (sourceRule ^. #allowedValues)-                             | not (null (sourceRule ^. #allowedValues)),-                               not (null unreachable)-                             ]-           in [EmptyConditionValues scope targetPath sourcePath | null normalizedValues]-                <> [SelfConditionalField scope targetPath | targetKey == sourceKey]-                <> sourceErrors--    referenceDefinitionErrors =-      List.nub $-        concatMap rawReferenceErrors scopedRules-          <> concatMap mergedReferenceErrors (rawSpec ^. #types)-      where-        declaredPrefixes = mapMaybe (^. #idPrefix) (rawSpec ^. #types)-        scopedRules =-          (Nothing, rawSpec ^. #frontmatter)-            : [(Just (rule ^. #type_), rule ^. #frontmatter) | rule <- rawSpec ^. #types]--        rawReferenceErrors (scope, rules) =-          concatMap topLevelPolicyErrors topLevelRules-            <> [ nestedError-               | rule <- topLevelRules,-                 nestedRules <- declaredNestedRuleSets rule,-                 nestedRule <- nestedRules ^. #required <> nestedRules ^. #recommended <> nestedRules ^. #optional,-                 nestedError <- policyErrors scope (nestedDefinitionPath (rule ^. #field) (nestedRule ^. #field)) (nestedRule ^. #format) (nestedRule ^. #reference) (nestedRule ^. #path)-               ]-          where-            topLevelRules = rules ^. #required <> rules ^. #recommended <> rules ^. #optional-            topLevelPolicyErrors rule =-              policyErrors scope (topLevelFieldPath (rule ^. #field)) (rule ^. #format) (rule ^. #reference) (rule ^. #path)--        policyErrors scope path declaredFormat handlePolicy pathPolicy =-          referencePolicyErrors scope path declaredFormat handlePolicy-            <> pathPolicyErrors scope path declaredFormat handlePolicy pathPolicy--        referencePolicyErrors scope path declaredFormat = \case-          Nothing -> []-          Just policy ->-            let prefix = policy ^. #localPrefix-                schemes = deduplicateSchemes (policy ^. #externalUriSchemes)-             in [InvalidReferencePrefix scope path prefix | not (validDocumentHandlePrefix prefix)]-                  <> [ReferencePrefixNotDeclared scope path prefix | prefix `notElem` declaredPrefixes]-                  <> [ReferenceRequiresIdField scope path | isNothing (rawSpec ^. #idField)]-                  <> [InvalidExternalReferenceScheme scope path scheme | scheme <- schemes, not (validUriScheme scheme)]-                  <> [ReferenceWithFormat scope path fieldFormat | Just fieldFormat <- [declaredFormat]]-                  <> [ InvalidExternalUriPattern scope path patternText detail-                     | Just patternText <- [policy ^. #externalUriPattern],-                       Left detail <- [compileExternalUriPattern patternText]-                     ]--        -- The three ways a path policy can be incoherent on its own. Two reuse-        -- the handle-reference constructors because the claim is identical: a-        -- scheme that is not a legal URI scheme, and a structural interpretation-        -- of a value paired with a textual format that would be checked against-        -- the same text. The third is genuinely new — a value cannot be resolved-        -- as both a @PREFIX-N@ handle and a §6.2 path — and cannot arise at-        -- nested scope, where 'NestedFieldRule' carries no handle policy.-        pathPolicyErrors scope path declaredFormat handlePolicy = \case-          Nothing -> []-          Just policy ->-            [ InvalidExternalReferenceScheme scope path scheme-            | scheme <- deduplicateSchemes (policy ^. #externalUriSchemes),-              not (validUriScheme scheme)-            ]-              <> [ReferenceWithFormat scope path fieldFormat | Just fieldFormat <- [declaredFormat]]-              <> [PathReferenceWithHandleReference scope path | isJust handlePolicy]--        mergedReferenceErrors typeRule =-          [ ConflictingReferencePrefix (typeRule ^. #type_) path (profilePolicy ^. #localPrefix) (typePolicy ^. #localPrefix)-          | (path, profileRule, typeFieldRule) <- pairedRules typeRule,-            Just profilePolicy <- [profileRule ^. #reference],-            Just typePolicy <- [typeFieldRule ^. #reference],-            profilePolicy ^. #localPrefix /= typePolicy ^. #localPrefix-          ]-            <> [ ConflictingExternalUriPatterns (typeRule ^. #type_) path profilePattern typePattern-               | (path, profileRule, typeFieldRule) <- pairedRules typeRule,-                 Just profilePattern <- [profileRule ^. #reference >>= (^. #externalUriPattern)],-                 Just typePattern <- [typeFieldRule ^. #reference >>= (^. #externalUriPattern)],-                 profilePattern /= typePattern-               ]-            <> [ ReferenceWithFormat (Just (typeRule ^. #type_)) path fieldFormat-               | (path, profileRule, typeFieldRule) <- pairedRules typeRule,-                 (referenceRule, formatRule) <- [(profileRule, typeFieldRule), (typeFieldRule, profileRule)],-                 isJust (referenceRule ^. #reference),-                 Just fieldFormat <- [formatRule ^. #format]-               ]-            <> [ PathReferenceWithHandleReference (Just (typeRule ^. #type_)) path-               | (path, profileRule, typeFieldRule) <- pairedRules typeRule,-                 (referenceRule, pathRule) <- [(profileRule, typeFieldRule), (typeFieldRule, profileRule)],-                 isJust (referenceRule ^. #reference),-                 isJust (pathRule ^. #path)-               ]--        pairedRules typeRule =-          [ (topLevelFieldPath key, profileRule, typeFieldRule)-          | let typeFields = compileRules (typeRule ^. #frontmatter),-            (key, (profileRule, typeFieldRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeFields)-          ]-            <> [ (nestedDefinitionPath parentKey nestedKey, profileNestedRule, typeNestedRule)-               | let typeFields = compileRules (typeRule ^. #frontmatter),-                 (parentKey, (profileRule, typeFieldRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeFields),-                 (profileNested, typeNested) <- pairedNestedRuleMaps profileRule typeFieldRule,-                 (nestedKey, (profileNestedRule, typeNestedRule)) <- Map.toAscList (Map.intersectionWith (,) profileNested typeNested)-               ]--    uniquenessDefinitionErrors =-      concatMap (validateDeclarations Nothing baseRules) [rawSpec ^. #frontmatter]-        <> concat-          [ let typeRules = compileRules (typeRule ^. #frontmatter)-             in validateDeclarations (Just (typeRule ^. #type_)) (mergeRules baseRules typeRules) (typeRule ^. #frontmatter)-          | typeRule <- rawSpec ^. #types-          ]-        <> [ ConflictingUniqueBy (typeRule ^. #type_) (topLevelFieldPath key) profileKey typeKey-           | typeRule <- rawSpec ^. #types,-             let typeRules = compileRules (typeRule ^. #frontmatter),-             (key, (profileRule, typeFieldRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),-             Just profileKey <- [profileRule ^. #uniqueBy],-             Just typeKey <- [typeFieldRule ^. #uniqueBy],-             profileKey /= typeKey-           ]-      where-        validateDeclarations scope effectiveRules rules =-          concatMap (validateDeclaration scope effectiveRules) (rules ^. #required <> rules ^. #recommended <> rules ^. #optional)--        validateDeclaration scope effectiveRules rawRule =-          case rawRule ^. #uniqueBy of-            Nothing -> []-            Just requestedKey ->-              let parentPath = topLevelFieldPath (rawRule ^. #field)-                  memberPath = nestedDefinitionPath (rawRule ^. #field) requestedKey-               in case Map.lookup (rawRule ^. #field) effectiveRules >>= (^. #elementFields) of-                    Nothing -> [UniqueByRequiresElementFields scope parentPath requestedKey]-                    Just memberRules ->-                      case Map.lookup requestedKey memberRules of-                        Nothing -> [UniqueByFieldNotDeclared scope memberPath]-                        Just memberRule ->-                          [ UniqueByFieldNotUnconditionallyRequired scope memberPath-                          | not (any unconditionalRequired (memberRule ^. #presenceClauses))-                          ]-                            <> [ UniqueByFieldNotScalar scope memberPath (memberRule ^. #cardinality)-                               | memberRule ^. #cardinality /= Scalar-                               ]--        unconditionalRequired clause =-          clause ^. #requirement == RequiredField && isNothing (clause ^. #condition)--    -- Only a value okf cannot parse is rejected. An unknown /major/ is-    -- deliberately accepted, unlike in @okfVersion@: there the profile is asking-    -- okf to interpret rules it may not understand, while here it is stating a-    -- minimum that a bundle's own declaration is compared against, which stays-    -- meaningful whatever the major is.-    requiredBundleVersionErrors =-      case rawSpec ^. #requireBundleVersion of-        Just rawVersion-          | isNothing (parseOkfVersion rawVersion) -> [InvalidRequiredBundleVersion rawVersion]-        _ -> []--    versionErrors =-      case effectiveProfileVersion (rawSpec ^. #okfVersion) of-        Left versionError -> [versionError]-        Right effectiveVersion ->-          let atLeastV02 = effectiveVersion >= okfVersion02-              v02Text = renderOkfVersion okfVersion02-              -- The /effective/ version, not the raw declared string: a profile-              -- declaring 0.9 is checked as 0.2 and its diagnostics should say so-              -- rather than repeating a number okf did not act on.-              declaredText = renderOkfVersion effectiveVersion-           in -- A key v0.2 superseded, demanded by a profile declaring v0.2 or-              -- later. Deliberately /not/ checked in the optional list: a team-              -- migrating a corpus wants @generated@ required and @timestamp@-              -- tolerated but not demanded, and the optional list says exactly-              -- that. This is the one check whose answer depends on which presence-              -- list a rule came from, so it reads the raw lists rather than the-              -- compiled map, which erases the distinction into presence clauses.-              [ FieldSupersededInOkfVersion scope (topLevelFieldPath (rule ^. #field)) declaredText v02Text-              | atLeastV02,-                (scope, rules) <- scopedFrontmatterRules,-                rule <- rules ^. #required <> rules ^. #recommended,-                rule ^. #field `elem` fieldsSupersededInV02-              ]-                -- The actor formats encode the specification §7 convention that-                -- v0.2 introduced. A format is an okf descriptor feature rather-                -- than a key name, so unlike the mirror case below it has no-                -- house-convention reading: @FieldFormat.Actor@ /is/ §7.-                <> [ FormatRequiresOkfVersion scope path fieldFormat declaredText v02Text-                   | not atLeastV02,-                     (scope, path, fieldFormat) <- scopedFormats,-                     fieldFormat `elem` [Actor, HumanActor]-                   ]--    -- There is deliberately no mirror check, "a profile declaring v0.1 names a-    -- key v0.2 introduced", which is why 'fieldsIntroducedInV02' is unused here.-    -- A profile key /name/ does not imply the OKF core key of that name: per-    -- docs/adr/1-profile-declared-document-ids.md, constraining keys the core-    -- format does not own is what profiles are for, and @status@, @sources@, and-    -- @verified@ are ordinary words teams were already using as house conventions-    -- before v0.2 claimed them. Such a check is both retroactive and ambiguous,-    -- which docs/adr/11-growing-the-profile-descriptor-language.md forbids.--    -- Every declared format paired with the path it sits at, top-level first and-    -- then nested. Only the format checks descend: 'fieldsIntroducedInV02' and-    -- 'fieldsSupersededInV02' name /concept-level/ frontmatter keys, so matching-    -- them against a member of a record would reject a profile whose element-    -- happens to be called @status@ for having a v0.2 key it does not have.-    scopedFormats =-      [ (scope, topLevelFieldPath (rule ^. #field), fieldFormat)-      | (scope, rules) <- scopedFrontmatterRules,-        rule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,-        Just fieldFormat <- [rule ^. #format]-      ]-        <> List.nub-          [ (scope, nestedDefinitionPath (rule ^. #field) (nestedRule ^. #field), fieldFormat)-          | (scope, rules) <- scopedFrontmatterRules,-            rule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,-            nestedRules <- declaredNestedRuleSets rule,-            nestedRule <- nestedRules ^. #required <> nestedRules ^. #recommended <> nestedRules ^. #optional,-            Just fieldFormat <- [nestedRule ^. #format]-          ]--    renderFieldPathKey (FieldPath (firstSegment :| remainingSegments)) =-      Text.intercalate "." (map renderSegment (firstSegment : remainingSegments))-    renderSegment (FieldName name) = name-    renderSegment (ArrayIndex elementIndex) = Text.pack (show elementIndex)---- | The OKF version that introduced the v0.2 frontmatter families and the actor--- convention. Written out rather than reusing 'supportedOkfVersion', which--- happens to equal it today: one is "what okf implements" and the other is "what--- introduced these keys", and they will diverge at the next minor bump.-okfVersion02 :: OkfVersion-okfVersion02 = OkfVersion {okfVersionMajor = 0, okfVersionMinor = 2}---- | The OKF version a profile's rules are checked against, or why okf cannot--- tell.------ A higher /minor/ within a known major is clamped, mirroring--- 'Okf.Validation.versionGate': specification §12 defines a minor bump as--- backward-compatible additions, so every rule a v0.3 profile can express is one--- okf already understands.------ An unknown /major/ is deliberately an error, where the bundle side reads--- best-effort — this is a considered divergence, not an oversight. §12's--- best-effort instruction is about bundles, which may come from a third party--- okf cannot ask. A profile is not a document okf is asked to read; it is an--- instruction to okf about what to check, written by an author who is present.--- Silently ignoring an instruction okf cannot interpret is worse than saying so.--- See @docs\/adr\/10-okf-version-declaration-and-best-effort-reading.md@.-effectiveProfileVersion :: Text -> Either ProfileDefinitionError OkfVersion-effectiveProfileVersion rawVersion =-  case parseOkfVersion rawVersion of-    Nothing -> Left (InvalidProfileOkfVersion rawVersion)-    Just declared-      | okfVersionMajor declared == okfVersionMajor supportedOkfVersion ->-          Right (min declared supportedOkfVersion)-      | otherwise -> Left (ProfileOkfVersionNotUnderstood rawVersion)--compileRules :: FrontmatterRules -> Map Text EffectiveFieldRule-compileRules FrontmatterRules {required, recommended, optional} =-  Map.fromList-    ( [ (rule ^. #field, compileFieldRule RequiredField rule)-      | rule <- required-      ]-        <> [ (rule ^. #field, compileFieldRule RecommendedField rule)-           | rule <- recommended-           ]-        <> [ (rule ^. #field, compileOptionalFieldRule rule)-           | rule <- optional-           ]-    )---- | Compile a rule the profile documents but never demands. It carries no--- presence clause, so 'applicablePresenceClause' can never find one to report in--- either validation mode, while every value check still runs from the--- present-value branch. This is also the value constraints a required or--- recommended rule is built from.-compileOptionalFieldRule :: FieldRule -> EffectiveFieldRule-compileOptionalFieldRule rule =-  EffectiveFieldRule-    { presenceClauses = [],-      description = rule ^. #description,-      allowedValues = deduplicate (rule ^. #allowedValues),-      cardinality =-        -- Declaring a nested shape and no explicit cardinality refines what the-        -- value may be, because the shape only makes sense against one. A rule-        -- declaring both shapes stays 'Any', which is what lets either spelling-        -- of the OKF v0.2 @verified@ key satisfy it.-        case (rule ^. #objectFields, rule ^. #elementFields, rule ^. #cardinality) of-          (Just _, Just _, Any) -> Any-          (Just _, Nothing, Any) -> Object-          (Nothing, Just _, Any) -> List-          (_, _, Any) -> refineCardinalityForFormat (rule ^. #format)-          (_, _, declared) -> declared,-      format = rule ^. #format,-      elementFields = compileNestedRules <$> rule ^. #elementFields,-      objectFields = compileNestedRules <$> rule ^. #objectFields,-      reference = compiledReference,-      path = compilePathRule <$> rule ^. #path,-      uniqueBy = rule ^. #uniqueBy,-      compiledExternalUriPattern = compileReferenceMatcher compiledReference-    }-  where-    compiledReference = compileReferenceRule <$> rule ^. #reference---- | The cardinality a rule with no declared one takes from its format.------ A non-textual format implies a scalar, and without this the rule would be--- useless: the 'Any' cardinality routes presence through 'legacyValueIsPresent',--- which counts only non-empty text and non-empty arrays, so a @usage_count:--- 5000@ is reported /missing/ before its value is ever examined. Refining here--- rather than widening 'legacyValueIsPresent' keeps the meaning of every--- descriptor that already exists — in particular a key whose value is @false@--- keeps being reported as missing when no rule says otherwise.------ An explicitly declared cardinality always wins, including @list@: a list of--- integers is a coherent thing to demand, so pairing a numeric format with--- 'List' is left alone rather than made an error.-refineCardinalityForFormat :: Maybe FieldFormat -> Cardinality-refineCardinalityForFormat = \case-  Just Integer -> Scalar-  Just NonNegativeInteger -> Scalar-  Just Boolean -> Scalar-  _ -> Any--compileFieldRule :: FieldRequirement -> FieldRule -> EffectiveFieldRule-compileFieldRule requirement rule =-  (compileOptionalFieldRule rule)-    { presenceClauses = [PresenceClause requirement (compileCondition <$> rule ^. #when)]-    }--compileNestedRules :: NestedRules -> Map Text EffectiveFieldRule-compileNestedRules NestedRules {required, recommended, optional} =-  Map.fromList-    ( [ (rule ^. #field, compileNestedFieldRule RequiredField rule)-      | rule <- required-      ]-        <> [ (rule ^. #field, compileNestedFieldRule RecommendedField rule)-           | rule <- recommended-           ]-        <> [ (rule ^. #field, compileOptionalNestedFieldRule rule)-           | rule <- optional-           ]-    )---- | The nested counterpart of 'compileOptionalFieldRule'.-compileOptionalNestedFieldRule :: NestedFieldRule -> EffectiveFieldRule-compileOptionalNestedFieldRule rule =-  EffectiveFieldRule-    { presenceClauses = [],-      description = rule ^. #description,-      allowedValues = deduplicate (rule ^. #allowedValues),-      cardinality =-        case rule ^. #cardinality of-          Any -> refineCardinalityForFormat (rule ^. #format)-          declared -> declared,-      format = rule ^. #format,-      elementFields = Nothing,-      -- Nested rules stay depth-bounded: 'NestedFieldRule' has no object member,-      -- so a profile cannot constrain @sources[0].usage_window.from@.-      objectFields = Nothing,-      reference = compiledReference,-      -- But it does carry a path policy, which is the point of the member —-      -- @sources[].resource@ is only reachable here.-      path = compilePathRule <$> rule ^. #path,-      uniqueBy = Nothing,-      compiledExternalUriPattern = compileReferenceMatcher compiledReference-    }-  where-    compiledReference = compileReferenceRule <$> rule ^. #reference--compileNestedFieldRule :: FieldRequirement -> NestedFieldRule -> EffectiveFieldRule-compileNestedFieldRule requirement rule =-  (compileOptionalNestedFieldRule rule)-    { presenceClauses = [PresenceClause requirement (compileCondition <$> rule ^. #when)]-    }--mergeRules :: Map Text EffectiveFieldRule -> Map Text EffectiveFieldRule -> Map Text EffectiveFieldRule-mergeRules = Map.unionWith mergeEffectiveFieldRule--mergeEffectiveFieldRule :: EffectiveFieldRule -> EffectiveFieldRule -> EffectiveFieldRule-mergeEffectiveFieldRule profileRule typeRule =-  EffectiveFieldRule-    { presenceClauses = profileRule ^. #presenceClauses <> typeRule ^. #presenceClauses,-      description = typeRule ^. #description <|> profileRule ^. #description,-      allowedValues = mergeVocabulary (profileRule ^. #allowedValues) (typeRule ^. #allowedValues),-      cardinality = mergeCardinality (profileRule ^. #cardinality) (typeRule ^. #cardinality),-      format = fromMaybe (profileRule ^. #format) (mergeFieldFormat (profileRule ^. #format) (typeRule ^. #format)),-      elementFields = mergeNestedRuleMaps (profileRule ^. #elementFields) (typeRule ^. #elementFields),-      objectFields = mergeNestedRuleMaps (profileRule ^. #objectFields) (typeRule ^. #objectFields),-      reference = mergedReference,-      path = mergePathRule (profileRule ^. #path) (typeRule ^. #path),-      uniqueBy = fromMaybe (profileRule ^. #uniqueBy) (mergeUniqueBy (profileRule ^. #uniqueBy) (typeRule ^. #uniqueBy)),-      compiledExternalUriPattern = compileReferenceMatcher mergedReference-    }-  where-    mergedReference = fromMaybe (profileRule ^. #reference) (mergeReferenceRule (profileRule ^. #reference) (typeRule ^. #reference))---- | Normalize a declared condition for storage in a 'PresenceClause': the shape--- is unchanged, but the accepted-value list is deduplicated so that a clause--- reported in a 'ProfileViolation' does not repeat a value the author wrote--- twice.-compileCondition :: FieldCondition -> FieldCondition-compileCondition rawCondition =-  FieldCondition-    { field = rawCondition ^. #field,-      hasValue = deduplicate (rawCondition ^. #hasValue)-    }--compileReferenceRule :: HandleReferenceRule -> HandleReferenceRule-compileReferenceRule policy =-  HandleReferenceRule-    { localPrefix = policy ^. #localPrefix,-      externalUriSchemes = map Text.toCaseFold (deduplicateSchemes (policy ^. #externalUriSchemes)),-      allowSelf = policy ^. #allowSelf,-      allowLocal = policy ^. #allowLocal,-      externalUriPattern = policy ^. #externalUriPattern-    }--compileExternalUriPattern :: Text -> Either Text Regex-compileExternalUriPattern patternText =-  first Text.pack (Regex.Text.compile defaultCompOpt defaultExecOpt patternText)--compileReferenceMatcher :: Maybe HandleReferenceRule -> Maybe Regex-compileReferenceMatcher policy = do-  patternText <- policy >>= (^. #externalUriPattern)-  either (const Nothing) Just (compileExternalUriPattern patternText)--matchesWholeExternalUriPattern :: Regex -> Text -> Bool-matchesWholeExternalUriPattern regex value =-  case Regex.Text.regexec regex value of-    Right (Just (before, _matched, after, _groups)) -> Text.null before && Text.null after-    _ -> False--compilePathRule :: PathReferenceRule -> PathReferenceRule-compilePathRule policy =-  PathReferenceRule-    { externalUriSchemes = map Text.toCaseFold (deduplicateSchemes (policy ^. #externalUriSchemes)),-      allowSelf = policy ^. #allowSelf-    }---- | Combine a profile-scope path policy with a type-scope one: intersect the--- permitted schemes and require both scopes to allow self-reference.------ Unlike 'mergeReferenceRule' this is total and needs no @Maybe@-of-@Maybe@--- result, because a path policy has no @localPrefix@ — the one thing two--- handle policies can flatly disagree about. Narrowing to the intersection is--- the same direction 'mergeVocabulary' takes: a type rule tightens the--- profile-wide rule and never loosens it.-mergePathRule :: Maybe PathReferenceRule -> Maybe PathReferenceRule -> Maybe PathReferenceRule-mergePathRule Nothing typePolicy = typePolicy-mergePathRule profilePolicy Nothing = profilePolicy-mergePathRule (Just profilePolicy) (Just typePolicy) =-  Just-    PathReferenceRule-      { externalUriSchemes =-          filter-            (`Set.member` Set.fromList (typePolicy ^. #externalUriSchemes))-            (profilePolicy ^. #externalUriSchemes),-        allowSelf = profilePolicy ^. #allowSelf && typePolicy ^. #allowSelf-      }---- | Merge one scope's map of member rules with another's. Used for both--- @elementFields@ and @objectFields@; it was named for the former until the--- latter existed and is a plain union-with-merge either way.-mergeNestedRuleMaps :: Maybe (Map Text EffectiveFieldRule) -> Maybe (Map Text EffectiveFieldRule) -> Maybe (Map Text EffectiveFieldRule)-mergeNestedRuleMaps Nothing typeRules = typeRules-mergeNestedRuleMaps profileRules Nothing = profileRules-mergeNestedRuleMaps (Just profileRules) (Just typeRules) = Just (Map.unionWith mergeEffectiveFieldRule profileRules typeRules)--mergeReferenceRule :: Maybe HandleReferenceRule -> Maybe HandleReferenceRule -> Maybe (Maybe HandleReferenceRule)-mergeReferenceRule Nothing typePolicy = Just typePolicy-mergeReferenceRule profilePolicy Nothing = Just profilePolicy-mergeReferenceRule (Just profilePolicy) (Just typePolicy)-  | profilePolicy ^. #localPrefix == typePolicy ^. #localPrefix,-    Just mergedPattern <- mergeOptionalText (profilePolicy ^. #externalUriPattern) (typePolicy ^. #externalUriPattern) =-      Just . Just $-        HandleReferenceRule-          { localPrefix = profilePolicy ^. #localPrefix,-            externalUriSchemes =-              filter-                (`Set.member` Set.fromList (typePolicy ^. #externalUriSchemes))-                (profilePolicy ^. #externalUriSchemes),-            allowSelf = profilePolicy ^. #allowSelf && typePolicy ^. #allowSelf,-            allowLocal = profilePolicy ^. #allowLocal && typePolicy ^. #allowLocal,-            externalUriPattern = mergedPattern-          }-  | otherwise = Nothing--mergeUniqueBy :: Maybe Text -> Maybe Text -> Maybe (Maybe Text)-mergeUniqueBy = mergeOptionalText--mergeOptionalText :: Maybe Text -> Maybe Text -> Maybe (Maybe Text)-mergeOptionalText Nothing typeValue = Just typeValue-mergeOptionalText profileValue Nothing = Just profileValue-mergeOptionalText profileValue typeValue-  | profileValue == typeValue = Just profileValue-  | otherwise = Nothing--mergeFieldFormat :: Maybe FieldFormat -> Maybe FieldFormat -> Maybe (Maybe FieldFormat)-mergeFieldFormat Nothing typeFormat = Just typeFormat-mergeFieldFormat profileFormat Nothing = Just profileFormat-mergeFieldFormat (Just Uri) (Just typeFormat@(UriWithScheme _)) = Just (Just typeFormat)-mergeFieldFormat (Just profileFormat@(UriWithScheme _)) (Just Uri) = Just (Just profileFormat)-mergeFieldFormat (Just Actor) (Just HumanActor) = Just (Just HumanActor)-mergeFieldFormat (Just HumanActor) (Just Actor) = Just (Just HumanActor)-mergeFieldFormat (Just Integer) (Just NonNegativeInteger) = Just (Just NonNegativeInteger)-mergeFieldFormat (Just NonNegativeInteger) (Just Integer) = Just (Just NonNegativeInteger)-mergeFieldFormat profileFormat typeFormat-  | profileFormat == typeFormat = Just profileFormat-  | otherwise = Nothing--invalidFormatParameter :: FieldFormat -> Maybe (FieldFormat, Text)-invalidFormatParameter fieldFormat =-  case fieldFormat of-    UriWithScheme scheme-      | not (validUriScheme scheme) -> Just (fieldFormat, scheme)-    DocumentHandle prefix-      | not (validDocumentHandlePrefix prefix) -> Just (fieldFormat, prefix)-    _ -> Nothing--validUriScheme :: Text -> Bool-validUriScheme scheme =-  case Text.uncons scheme of-    Just (firstCharacter, rest) -> isAsciiLetter firstCharacter && Text.all validRest rest-    Nothing -> False-  where-    validRest character =-      isAsciiLetter character-        || ('0' <= character && character <= '9')-        || character `elem` ['+', '.', '-']--validDocumentHandlePrefix :: Text -> Bool-validDocumentHandlePrefix prefix =-  case parseDocumentId (prefix <> "-1") of-    Just documentId -> documentId ^. #prefix == prefix-    Nothing -> False--isAsciiLetter :: Char -> Bool-isAsciiLetter character = isAsciiLower character || isAsciiUpper character--mergeCardinality :: Cardinality -> Cardinality -> Cardinality-mergeCardinality Any typeCardinality = typeCardinality-mergeCardinality profileCardinality Any = profileCardinality-mergeCardinality profileCardinality _typeCardinality = profileCardinality--mergeVocabulary :: [Text] -> [Text] -> [Text]-mergeVocabulary [] typeValues = typeValues-mergeVocabulary profileValues [] = profileValues-mergeVocabulary profileValues typeValues =-  filter (`Set.member` Set.fromList typeValues) profileValues--deduplicate :: [Text] -> [Text]-deduplicate = go Set.empty-  where-    go _ [] = []-    go seen (value : rest)-      | value `Set.member` seen = go seen rest-      | otherwise = value : go (Set.insert value seen) rest--deduplicateSchemes :: [Text] -> [Text]-deduplicateSchemes = go Set.empty-  where-    go _ [] = []-    go seen (scheme : rest)-      | normalized `Set.member` seen = go seen rest-      | otherwise = scheme : go (Set.insert normalized seen) rest-      where-        normalized = Text.toCaseFold scheme--effectiveRulesForType :: CompiledProfile -> Text -> Map Text EffectiveFieldRule-effectiveRulesForType compiled ctype =-  Map.findWithDefault (compiled ^. #baseRules) ctype (compiled ^. #rulesByType)--profileFieldDescriptionForType :: CompiledProfile -> Text -> Text -> Maybe Text-profileFieldDescriptionForType compiled ctype key =-  Map.lookup key (effectiveRulesForType compiled ctype) >>= (^. #description)---- | A parsed document handle: an ASCII-letter-led alphanumeric prefix and a--- positive number, rendered as @PREFIX-N@.-data DocumentId = DocumentId-  { prefix :: !Text,-    number :: !Natural-  }-  deriving stock (Generic, Eq, Ord, Show)---- | Parse a strict document handle. The prefix contains one or more ASCII--- letters or digits and begins with a letter. It is followed by exactly one--- hyphen and a positive decimal number with no leading zero. Thus @ADR-7@--- parses, while @ADR-007@, @ADR-0@, @ADR-@, @-7@, @adr 7@, and--- @ADR-7-extra@ do not.-parseDocumentId :: Text -> Maybe DocumentId-parseDocumentId raw =-  case Text.splitOn "-" raw of-    [prefixText, numberText]-      | validPrefix prefixText,-        validNumberText numberText ->-          case Text.Read.decimal numberText of-            Right (parsedNumber, remainder)-              | Text.null remainder,-                parsedNumber > 0 ->-                  Just (DocumentId prefixText parsedNumber)-            _ -> Nothing-    _ -> Nothing-  where-    validPrefix value =-      case Text.uncons value of-        Just (firstCharacter, rest) ->-          isAsciiLetter firstCharacter && Text.all isAsciiAlphaNumeric rest-        Nothing -> False-    validNumberText value =-      case Text.uncons value of-        Just (firstCharacter, rest) ->-          firstCharacter >= '1'-            && firstCharacter <= '9'-            && Text.all isAsciiDigit rest-        Nothing -> False-    isAsciiDigit character =-      character >= '0' && character <= '9'-    isAsciiAlphaNumeric character =-      isAsciiLetter character || isAsciiDigit character---- | Render a document handle as @PREFIX-N@.-renderDocumentId :: DocumentId -> Text-renderDocumentId DocumentId {prefix, number} =-  prefix <> "-" <> Text.pack (show number)---- | Every well-formed handle under the profile's ID field, paired with the--- concept carrying it and sorted by prefix, number, then concept ID. Concepts--- without a well-formed handle are omitted. A profile with no ID field yields--- an empty list.-documentIdsInBundle :: ProfileSpec -> [Concept] -> [(DocumentId, ConceptId)]-documentIdsInBundle spec concepts =-  case spec ^. #idField of-    Nothing -> []-    Just fieldName ->-      List.sortOn-        (\(documentId, cid) -> (documentId, renderConceptId cid))-        [ (documentId, conceptIdOf concept)-        | concept <- concepts,-          Just (String rawDocumentId) <- [frontmatterLookup fieldName (conceptFrontmatter concept)],-          Just documentId <- [parseDocumentId rawDocumentId]-        ]---- | Allocate one more than the highest document-ID number already used for the--- given prefix, or number 1 when the prefix is unused. Gaps are deliberately--- not filled: reusing a retired number could make an old reference silently--- point at a different document.-nextDocumentId :: ProfileSpec -> [Concept] -> Text -> DocumentId-nextDocumentId spec concepts requestedPrefix =-  DocumentId-    { prefix = requestedPrefix,-      number = highestNumber + 1-    }-  where-    highestNumber =-      List.foldl'-        max-        0-        [ documentId ^. #number-        | (documentId, _) <- documentIdsInBundle spec concepts,-          documentId ^. #prefix == requestedPrefix-        ]---- | One structural segment of a frontmatter path. EP-2 produces top-level--- 'FieldName' paths; later bounded nested validation can append field names and--- array indexes without encoding paths as ad hoc text.-data FieldPathSegment-  = FieldName Text-  | ArrayIndex Int-  deriving stock (Generic, Eq, Ord, Show)--newtype FieldPath = FieldPath-  { segments :: NonEmpty FieldPathSegment-  }-  deriving stock (Generic, Eq, Ord, Show)--topLevelFieldPath :: Text -> FieldPath-topLevelFieldPath key = FieldPath (FieldName key :| [])--nestedDefinitionPath :: Text -> Text -> FieldPath-nestedDefinitionPath parent child =-  FieldPath (FieldName parent :| [FieldName child])--nestedValuePath :: Text -> Int -> Text -> FieldPath-nestedValuePath parent elementIndex child =-  FieldPath (FieldName parent :| [ArrayIndex elementIndex, FieldName child])--nestedElementPath :: Text -> Int -> FieldPath-nestedElementPath parent elementIndex =-  FieldPath (FieldName parent :| [ArrayIndex elementIndex])---- | A single deviation from a profile. Advisory by default at the CLI layer.-data ProfileViolation-  = -- | concept's @type@ is not listed in the profile and unknown types are disallowed-    TypeNotInProfile ConceptId Text-  | -- | a required frontmatter key is missing or empty (concept, key, activating condition)-    MissingProfileField ConceptId Text (Maybe FieldCondition)-  | -- | a recommended frontmatter key is missing under strict authoring-    MissingRecommendedProfileField ConceptId Text (Maybe FieldCondition)-  | -- | a required field is missing inside one list element record-    MissingNestedProfileField ConceptId FieldPath (Maybe FieldCondition)-  | -- | a recommended nested field is missing under strict authoring-    MissingRecommendedNestedProfileField ConceptId FieldPath (Maybe FieldCondition)-  | -- | a present value is outside the effective textual vocabulary-    ValueNotInVocabulary ConceptId FieldPath [Text] Value-  | -- | a present value has the wrong scalar/list shape-    CardinalityMismatch ConceptId FieldPath Cardinality Value-  | -- | a present value does not satisfy its named textual format-    ValueFormatMismatch ConceptId FieldPath FieldFormat Value-  | -- | a local reference has the right prefix but no valid owner in this bundle-    DanglingHandleReference ConceptId FieldPath Text-  | -- | a parsed local handle uses a prefix other than the declared target prefix-    ReferenceHandlePrefixMismatch ConceptId FieldPath Text Text-  | -- | a reference value is neither textual local handle nor valid absolute URI-    MalformedDocumentReference ConceptId FieldPath Value-  | -- | an absolute external URI uses a scheme the profile did not permit-    ExternalReferenceSchemeNotAllowed ConceptId FieldPath Text [Text]-  | -- | a syntactically valid local handle is prohibited at this field-    LocalDocumentReferenceNotAllowed ConceptId FieldPath Text-  | -- | an allowed external URI does not match the declared whole-value pattern-    ExternalReferencePatternMismatch ConceptId FieldPath Text Text-  | -- | a local handle, or a bundle path, resolves to the concept carrying it-    SelfDocumentReference ConceptId FieldPath Text-  | -- | a path-valued field's value is not one of the three shapes of §6.2-    MalformedPathReference ConceptId FieldPath Value-  | -- | a relative path climbs above the bundle root-    PathEscapesBundle ConceptId FieldPath Text-  | -- | a bundle path names a concept that does not exist in this bundle-    DanglingPathReference ConceptId FieldPath Text-  | -- | a closed profile does not declare this top-level field-    FieldNotInProfile ConceptId Text-  | -- | a declared list element is not an object record-    NestedElementNotRecord ConceptId FieldPath Value-  | -- | one valid scalar member value occurs in more than one list element-    DuplicateNestedFieldValue ConceptId FieldPath Value (NonEmpty Int)-  | -- | concept's file path does not match the type rule's pattern (concept, type, pattern)-    PathPatternMismatch ConceptId Text Text-  | -- | type rule requires a resource scheme but resource is absent (concept, type, scheme)-    MissingResource ConceptId Text Text-  | -- | resource present but its scheme is wrong (concept, expected scheme, actual resource)-    ResourceSchemeMismatch ConceptId Text Text-  | -- | required @# Schema@ section is absent (concept, type)-    MissingSchemaSection ConceptId Text-  | -- | @# Schema@ table columns do not match (concept, type, expected, actual)-    SchemaColumnsMismatch ConceptId Text [Text] [Text]-  | -- | type rule declares an @idPrefix@ but the concept has no handle (concept, type, prefix)-    MissingDocumentId ConceptId Text Text-  | -- | handle present but malformed for the declared prefix (concept, prefix, actual value)-    MalformedDocumentId ConceptId Text Text-  | -- | the same handle appears on more than one concept (handle, concept, other concept)-    DuplicateDocumentId Text ConceptId ConceptId-  | -- | the profile requires the bundle to declare an OKF version it does not-    -- (required version, what the bundle declared, 'Nothing' when undeclared)-    ---    -- The only violation that belongs to the bundle rather than to a concept, so-    -- a consumer grouping violations by 'ConceptId' has nothing to key it on.-    RequiredBundleVersionUnmet Text (Maybe Text)-  deriving stock (Generic, Eq, Show)---- | Check every concept against a compiled profile, returning all deviations.--- Profile-wide rules apply even to unknown types; a matching type rule adds its--- frontmatter rules and the existing type-specific structural checks.------ Existence is decided against the concepts themselves, so a @path@ rule can--- tell whether a target names a concept and cannot tell whether it names--- @references\/attesters\/revenue.py@; such a target is accepted unchecked.--- Callers holding a real directory should use 'validateProfileWith'.-validateProfile :: ValidationProfile -> CompiledProfile -> [Concept] -> [ProfileViolation]-validateProfile =-  validateProfileWithPresence conceptsOnly bundleInventoryOfConcepts-  where-    -- Narrowed to @.md@ on purpose. A caller with concepts and no directory can-    -- decide a @.md@ target, because a 'Concept' /is/ a non-reserved @.md@-    -- file — but it has never been able to see §6.3's-    -- @references/attesters/revenue.py@, and answering 'TargetAbsent' for it-    -- would turn a question okf cannot ask into a rejection.-    conceptsOnly conceptInventory resolved-      | FilePath.takeExtension resolved /= ".md" = TargetUnknown-      | bundleInventoryMember resolved conceptInventory = TargetPresent-      | otherwise = TargetAbsent---- | 'validateProfile' with the bundle's full file inventory, so a @path@ rule--- can decide whether a target that is not a concept exists.------ Specification §6.3's own example of a path target is--- @references\/attesters\/revenue.py@, which is not a concept and which--- 'validateProfile' therefore accepts unchecked. A caller that walked a real--- directory has 'Okf.Bundle.walkBundleInventory' and can do better. See--- @docs\/adr\/13-the-references-convention-and-non-markdown-files.md@.------ Passing an inventory does not make validation touch the filesystem. The--- inventory is data read once during the bundle walk, where okf is already doing--- IO, which is the shape @docs\/adr\/5-compile-profile-rules-before-validation.md@--- requires and the one the core §6.2 check already uses.-validateProfileWith :: BundleInventory -> ValidationProfile -> CompiledProfile -> [Concept] -> [ProfileViolation]-validateProfileWith inventory =-  validateProfileWithPresence everyFile (const inventory)-  where-    everyFile fullInventory resolved-      | bundleInventoryMember resolved fullInventory = TargetPresent-      | otherwise = TargetAbsent---- | Check a bundle's specification §12 version declaration against the profile's--- @requireBundleVersion@ setting. Returns @[]@ when the profile requires nothing,--- which is the default and the case for almost every profile.------ Deliberately a separate entry point rather than a parameter on--- 'validateProfile' and 'validateProfileWith'. Those two are public and their--- signatures are depended on downstream, and this check consults no concepts at--- all: threading a bundle-scoped question through a concept-walking function--- would be misleading as well as breaking.------ §12 makes the declaration a MAY, so okf's own validator never asks for one —--- see @docs\/adr\/10-okf-version-declaration-and-best-effort-reading.md@. This is--- the house-convention half: nothing is reported unless a profile author wrote--- the field.------ A declaration okf cannot parse counts as unmet. It cannot be compared, okf--- already reports it separately as a strict-mode authoring lint, and silently--- passing it would let a typo satisfy a requirement.-validateProfileVersion :: VersionDeclaration -> CompiledProfile -> [ProfileViolation]-validateProfileVersion declaration compiled =-  case compiledProfileRequiredBundleVersion compiled of-    Nothing -> []-    Just required ->-      let unmet = [RequiredBundleVersionUnmet (renderOkfVersion required) declaredText]-       in case declaration of-            -- A bundle ahead of the house minimum is not a deviation: §12 defines-            -- a minor bump as backward-compatible additions.-            VersionDeclared declared | declared >= required -> []-            VersionDeclared _ -> unmet-            VersionUnparseable _ -> unmet-            VersionUndeclared -> unmet-  where-    declaredText = case declaration of-      VersionDeclared declared -> Just (renderOkfVersion declared)-      VersionUnparseable rawVersion -> Just rawVersion-      VersionUndeclared -> Nothing---- | The shared body of 'validateProfile' and 'validateProfileWith'.------ The first argument decides what a @path@ rule may conclude about a resolved--- §6.2 target; the second supplies the inventory it consults, derived from the--- concepts when the caller has no directory to walk. Keeping one implementation--- is what stops the two entry points from drifting apart on everything /except/--- the one question that distinguishes them.-validateProfileWithPresence ::-  (BundleInventory -> FilePath -> PathTargetPresence) ->-  ([Concept] -> BundleInventory) ->-  ValidationProfile ->-  CompiledProfile ->-  [Concept] ->-  [ProfileViolation]-validateProfileWithPresence presenceRule inventoryOf validationProfile compiled concepts =-  concatMap checkConcept sortedConcepts <> checkDuplicateDocumentIds spec sortedConcepts-  where-    spec = compiledProfileSpec compiled-    sortedConcepts = List.sortOn (renderConceptId . conceptIdOf) concepts-    rulesByType = [(rule ^. #type_, rule) | rule <- spec ^. #types]-    validDocumentIdIndex = buildValidDocumentIdIndex spec rulesByType sortedConcepts-    -- What this caller can say about a resolved §6.2 path, built once.-    presenceOf = presenceRule (inventoryOf sortedConcepts)--    checkConcept concept =-      let cid = conceptIdOf concept-          ctype = conceptType concept-          fieldViolations = checkFields cid ctype concept <> checkUnknownFields cid ctype concept-       in case lookup ctype rulesByType of-            Nothing ->-              [TypeNotInProfile cid ctype | not (spec ^. #allowUnknownTypes)] <> fieldViolations-            Just rule ->-              fieldViolations-                <> checkPath cid ctype rule-                <> checkResource cid ctype rule concept-                <> checkSchema cid ctype rule concept-                <> checkDocumentId spec cid ctype rule concept--    checkFields cid ctype concept =-      concatMap checkField (Map.toAscList (effectiveRulesForType compiled ctype))-      where-        checkField (key, rule) =-          case evaluateFieldValue rule (frontmatterLookup key (conceptFrontmatter concept)) of-            FieldAbsent actual ->-              presenceViolations key rule-                <> maybe [] (vocabularyViolations key rule) actual-                <> maybe [] (formatViolations key rule) actual-                <> maybe [] (referenceViolations (topLevelFieldPath key) rule) actual-                <> maybe [] (pathViolations (topLevelFieldPath key) rule) actual-            FieldPresent actual ->-              vocabularyViolations key rule actual-                <> formatViolations key rule actual-                <> referenceViolations (topLevelFieldPath key) rule actual-                <> pathViolations (topLevelFieldPath key) rule actual-                <> nestedViolations key rule actual-                <> objectViolations key rule actual-            FieldWrongShape actual -> [CardinalityMismatch cid (topLevelFieldPath key) (rule ^. #cardinality) actual]--        presenceViolations key rule =-          case applicablePresenceClause validationProfile (\sourceKey -> frontmatterLookup sourceKey (conceptFrontmatter concept)) rule of-            Nothing -> []-            Just clause ->-              [ case clause ^. #requirement of-                  RequiredField -> MissingProfileField cid key (clause ^. #condition)-                  RecommendedField -> MissingRecommendedProfileField cid key (clause ^. #condition)-              ]-        vocabularyViolations key rule actual =-          [ ValueNotInVocabulary cid (topLevelFieldPath key) (rule ^. #allowedValues) actual-          | not (null (rule ^. #allowedValues)),-            not (valueMatchesVocabulary (rule ^. #allowedValues) actual)-          ]-        formatViolations key rule actual =-          [ ValueFormatMismatch cid (topLevelFieldPath key) fieldFormat actual-          | Just fieldFormat <- [rule ^. #format],-            not (valueMatchesFormat fieldFormat actual)-          ]-        referenceViolations fieldPath rule actual =-          case rule ^. #reference of-            Nothing -> []-            Just policy -> validateReferenceValue validDocumentIdIndex cid fieldPath policy (rule ^. #compiledExternalUriPattern) actual--        -- Takes a 'FieldPath' rather than a key because it is shared by all-        -- three scopes: a top-level key, a member of a list element, and a-        -- member of an object-valued mapping.-        pathViolations fieldPath rule actual =-          case rule ^. #path of-            Nothing -> []-            Just policy -> validatePathValue presenceOf cid fieldPath policy actual--        nestedViolations parentKey parentRule = \case-          Array elementValues-            | Just nestedRules <- parentRule ^. #elementFields ->-                let indexedElements = zip [0 ..] (Vector.toList elementValues)-                 in concat-                      [ case elementValue of-                          Aeson.Object members ->-                            concatMap-                              (checkRecordMember (nestedValuePath parentKey elementIndex) members)-                              (Map.toAscList nestedRules)-                          _ -> [NestedElementNotRecord cid (nestedElementPath parentKey elementIndex) elementValue]-                      | (elementIndex, elementValue) <- indexedElements-                      ]-                      <> uniquenessViolations parentKey parentRule nestedRules indexedElements-          _ -> []--        -- The mapping spelling of the same idea. The value /is/ the record, so-        -- there is no index in the path: a member is reported as-        -- @generated.by@ rather than @generated[0].by@.-        objectViolations parentKey parentRule = \case-          Aeson.Object members-            | Just objectRules <- parentRule ^. #objectFields ->-                concatMap-                  (checkRecordMember (nestedDefinitionPath parentKey) members)-                  (Map.toAscList objectRules)-          _ -> []--        -- Check one member of one record. Shared by the list-element and-        -- object-value walks, which differ only in how they name the member;-        -- the sibling lookup that resolves a @when@ condition stays scoped to-        -- the record the member lives in either way.-        checkRecordMember buildPath members (key, rule) =-          let path = buildPath key-              actualValue = Aeson.KeyMap.lookup (Aeson.Key.fromText key) members-           in case evaluateFieldValue rule actualValue of-                FieldAbsent actual ->-                  nestedPresenceViolations members path rule-                    <> maybe [] (nestedVocabularyViolations path rule) actual-                    <> maybe [] (nestedFormatViolations path rule) actual-                    <> maybe [] (referenceViolations path rule) actual-                    <> maybe [] (pathViolations path rule) actual-                FieldPresent actual ->-                  nestedVocabularyViolations path rule actual-                    <> nestedFormatViolations path rule actual-                    <> referenceViolations path rule actual-                    <> pathViolations path rule actual-                FieldWrongShape actual -> [CardinalityMismatch cid path (rule ^. #cardinality) actual]--        nestedPresenceViolations objectFields path rule =-          case applicablePresenceClause validationProfile lookupSibling rule of-            Nothing -> []-            Just clause ->-              [ case clause ^. #requirement of-                  RequiredField -> MissingNestedProfileField cid path (clause ^. #condition)-                  RecommendedField -> MissingRecommendedNestedProfileField cid path (clause ^. #condition)-              ]-          where-            lookupSibling sourceKey = Aeson.KeyMap.lookup (Aeson.Key.fromText sourceKey) objectFields-        nestedVocabularyViolations path rule actual =-          [ ValueNotInVocabulary cid path (rule ^. #allowedValues) actual-          | not (null (rule ^. #allowedValues)),-            not (valueMatchesVocabulary (rule ^. #allowedValues) actual)-          ]-        nestedFormatViolations path rule actual =-          [ ValueFormatMismatch cid path fieldFormat actual-          | Just fieldFormat <- [rule ^. #format],-            not (valueMatchesFormat fieldFormat actual)-          ]--        uniquenessViolations parentKey parentRule nestedRules indexedElements =-          case parentRule ^. #uniqueBy of-            Nothing -> []-            Just key ->-              case Map.lookup key nestedRules of-                Nothing -> []-                Just keyRule ->-                  [ DuplicateNestedFieldValue cid (nestedDefinitionPath parentKey key) duplicateValue (firstIndex :| remainingIndices)-                  | (duplicateValue, firstIndex : remainingIndices) <- groupedValues key keyRule indexedElements,-                    not (null remainingIndices)-                  ]--        groupedValues key keyRule =-          List.foldl' insertValue [] . mapMaybe participant-          where-            participant (elementIndex, Aeson.Object members) =-              case evaluateFieldValue keyRule (Aeson.KeyMap.lookup (Aeson.Key.fromText key) members) of-                FieldPresent scalarValue -> Just (scalarValue, elementIndex)-                _ -> Nothing-            participant _ = Nothing--            insertValue [] (value, elementIndex) = [(value, [elementIndex])]-            insertValue ((groupValue, elementIndices) : remaining) (value, elementIndex)-              | groupValue == value = (groupValue, elementIndices <> [elementIndex]) : remaining-              | otherwise = (groupValue, elementIndices) : insertValue remaining (value, elementIndex)--    checkUnknownFields cid ctype concept-      | spec ^. #allowUnknownFields = []-      | otherwise =-          [ FieldNotInProfile cid key-          | key <- frontmatterKeys (conceptFrontmatter concept),-            key `Set.notMember` allowedFields ctype-          ]--    allowedFields ctype =-      coreFrontmatterFields-        <> Map.keysSet (effectiveRulesForType compiled ctype)-        <> maybe Set.empty Set.singleton (spec ^. #idField)---- | Index only handles that are valid owners under the compiled profile's raw--- type declarations: the concept has a matching type rule, that rule declares--- the parsed handle's exact prefix, and the profile declares the owning field.--- Multiple owners are retained so a duplicate target still counts as existing;--- the existing bundle-wide duplicate diagnostic remains authoritative.-buildValidDocumentIdIndex :: ProfileSpec -> [(Text, TypeRule)] -> [Concept] -> Map DocumentId [ConceptId]-buildValidDocumentIdIndex spec rulesByType concepts =-  case spec ^. #idField of-    Nothing -> Map.empty-    Just fieldName ->-      Map.fromListWith-        (flip (<>))-        [ (documentId, [conceptIdOf concept])-        | concept <- concepts,-          Just typeRule <- [lookup (conceptType concept) rulesByType],-          Just expectedPrefix <- [typeRule ^. #idPrefix],-          Just (String rawDocumentId) <- [frontmatterLookup fieldName (conceptFrontmatter concept)],-          Just documentId <- [parseDocumentId rawDocumentId],-          documentId ^. #prefix == expectedPrefix-        ]--validateReferenceValue :: Map DocumentId [ConceptId] -> ConceptId -> FieldPath -> HandleReferenceRule -> Maybe Regex -> Value -> [ProfileViolation]-validateReferenceValue validOwners sourceConcept path policy matcher = \case-  String rawReference -> validateReferenceText validOwners sourceConcept path policy matcher rawReference-  Array values ->-    concat-      [ case value of-          String rawReference -> validateReferenceText validOwners sourceConcept (appendArrayIndex path elementIndex) policy matcher rawReference-          _ -> [MalformedDocumentReference sourceConcept (appendArrayIndex path elementIndex) value]-      | (elementIndex, value) <- zip [0 ..] (Vector.toList values)-      ]-  actual -> [MalformedDocumentReference sourceConcept path actual]--validateReferenceText :: Map DocumentId [ConceptId] -> ConceptId -> FieldPath -> HandleReferenceRule -> Maybe Regex -> Text -> [ProfileViolation]-validateReferenceText validOwners sourceConcept path policy matcher rawReference =-  case parseDocumentId rawReference of-    Just documentId-      | not (policy ^. #allowLocal) ->-          [LocalDocumentReferenceNotAllowed sourceConcept path rawReference]-      | documentId ^. #prefix /= policy ^. #localPrefix ->-          [ReferenceHandlePrefixMismatch sourceConcept path rawReference (policy ^. #localPrefix)]-      | otherwise ->-          case Map.lookup documentId validOwners of-            Nothing -> [DanglingHandleReference sourceConcept path rawReference]-            Just owners-              | not (policy ^. #allowSelf),-                sourceConcept `elem` owners ->-                  [SelfDocumentReference sourceConcept path rawReference]-              | otherwise -> []-    Nothing ->-      case parseURI (Text.unpack rawReference) of-        Just parsed-          | not (Text.null normalizedScheme),-            normalizedScheme `elem` policy ^. #externalUriSchemes ->-              case (policy ^. #externalUriPattern, matcher) of-                (Nothing, _) -> []-                (Just patternText, Just compiledPattern)-                  | matchesWholeExternalUriPattern compiledPattern rawReference -> []-                  | otherwise -> [ExternalReferencePatternMismatch sourceConcept path rawReference patternText]-                (Just patternText, Nothing) -> [ExternalReferencePatternMismatch sourceConcept path rawReference patternText]-          | not (Text.null normalizedScheme) ->-              [ ExternalReferenceSchemeNotAllowed-                  sourceConcept-                  path-                  normalizedScheme-                  (policy ^. #externalUriSchemes)-              ]-          | otherwise -> [MalformedDocumentReference sourceConcept path (String rawReference)]-          where-            normalizedScheme = Text.toCaseFold (Text.dropWhileEnd (== ':') (Text.pack (uriScheme parsed)))-        Nothing -> [MalformedDocumentReference sourceConcept path (String rawReference)]---- | Check one path-valued frontmatter value, at any scope. A list is checked--- element-wise so that a diagnostic names @sources[1].resource@ rather than the--- whole list.-validatePathValue :: (FilePath -> PathTargetPresence) -> ConceptId -> FieldPath -> PathReferenceRule -> Value -> [ProfileViolation]-validatePathValue presenceOf sourceConcept path policy = \case-  String rawPath -> validatePathText presenceOf sourceConcept path policy rawPath-  Array values ->-    concat-      [ case value of-          String rawPath ->-            validatePathText presenceOf sourceConcept (appendArrayIndex path elementIndex) policy rawPath-          _ -> [MalformedPathReference sourceConcept (appendArrayIndex path elementIndex) value]-      | (elementIndex, value) <- zip [0 ..] (Vector.toList values)-      ]-  actual -> [MalformedPathReference sourceConcept path actual]---- | What a caller can say about a resolved §6.2 bundle path.------ Three answers rather than two, because "I cannot tell" is a real state and--- collapsing it into "absent" turns silence into a rejection. 'validateProfile'--- is handed concepts alone, so it genuinely cannot say whether §6.3's--- @references\/attesters\/revenue.py@ is there, and reporting it as dangling--- would be a claim okf did not check.-data PathTargetPresence-  = -- | The bundle holds it.-    TargetPresent-  | -- | The bundle does not hold it, and the caller can see enough to be sure.-    TargetAbsent-  | -- | The caller cannot answer for this path.-    TargetUnknown-  deriving stock (Generic, Eq, Show)---- | Check one path value against the §6.2 grammar and the profile's policy.------ Every diagnostic carries the raw text the author wrote rather than the--- collapsed path okf computed from it, so the message names something findable--- in the file.------ Existence is decided by the supplied lookup, which reports what the caller can--- actually see: 'validateProfileWith' holds a real directory's inventory and so--- resolves §6.3's own @references\/attesters\/revenue.py@, while--- 'validateProfile' holds the concepts alone and answers 'TargetUnknown' for it.------ The @.md@ branch still goes through 'conceptIdFromFilePath', because that is--- what decides self-reference and what makes 'MalformedPathReference' reachable--- for a path no concept ID could be built from. What it no longer decides is--- whether the target is there.-validatePathText :: (FilePath -> PathTargetPresence) -> ConceptId -> FieldPath -> PathReferenceRule -> Text -> [ProfileViolation]-validatePathText presenceOf sourceConcept path policy rawPath =-  case classifyPathReference sourceConcept rawPath of-    ExternalUrl scheme-      | scheme `elem` policy ^. #externalUriSchemes -> []-      | otherwise ->-          [ExternalReferenceSchemeNotAllowed sourceConcept path scheme (policy ^. #externalUriSchemes)]-    EscapesBundle -> [PathEscapesBundle sourceConcept path rawPath]-    MalformedPath -> [MalformedPathReference sourceConcept path (String rawPath)]-    BundlePath resolved-      | FilePath.takeExtension resolved == ".md" ->-          case conceptIdFromFilePath resolved of-            Left _ -> [MalformedPathReference sourceConcept path (String rawPath)]-            Right target-              | target == sourceConcept,-                not (policy ^. #allowSelf) ->-                  [SelfDocumentReference sourceConcept path rawPath]-              | otherwise -> danglingWhenAbsent resolved-      | otherwise -> danglingWhenAbsent resolved-  where-    danglingWhenAbsent resolved = case presenceOf resolved of-      TargetAbsent -> [DanglingPathReference sourceConcept path rawPath]-      TargetPresent -> []-      TargetUnknown -> []--appendArrayIndex :: FieldPath -> Int -> FieldPath-appendArrayIndex (FieldPath pathSegments) elementIndex =-  FieldPath (pathSegments <> (ArrayIndex elementIndex :| []))--applicablePresenceClause :: ValidationProfile -> (Text -> Maybe Value) -> EffectiveFieldRule -> Maybe PresenceClause-applicablePresenceClause validationProfile lookupValue rule =-  List.find applies requiredClauses-    <|> if validationProfile == StrictAuthoring then List.find applies recommendedClauses else Nothing-  where-    requiredClauses = filter ((== RequiredField) . (^. #requirement)) (rule ^. #presenceClauses)-    recommendedClauses = filter ((== RecommendedField) . (^. #requirement)) (rule ^. #presenceClauses)-    applies clause = maybe True conditionApplies (clause ^. #condition)-    conditionApplies condition =-      case lookupValue (condition ^. #field) of-        Just (String actual) -> actual `elem` condition ^. #hasValue-        _ -> False--valueMatchesVocabulary :: [Text] -> Value -> Bool-valueMatchesVocabulary allowed = \case-  String value -> value `elem` allowed-  Array values -> all elementMatches (Vector.toList values)-  _ -> False-  where-    elementMatches (String value) = value `elem` allowed-    elementMatches _ = False---- | Whether a present value satisfies a format. Each format declares which--- value shapes it can match at all: the textual formats match a string, the--- numeric ones a YAML number, and 'Boolean' a YAML boolean. A list is matched--- by recursing, so a list of integers satisfies an @integer@ format for the--- same reason a list of timestamps satisfies @rfc3339-utc@ — a format--- constrains a value, and a list is a list of values.-valueMatchesFormat :: FieldFormat -> Value -> Bool-valueMatchesFormat fieldFormat actual =-  case actual of-    String value -> textMatchesFormat fieldFormat value-    Array values -> all (valueMatchesFormat fieldFormat) (Vector.toList values)-    Number _ -> numberMatchesFormat fieldFormat actual-    Bool _ -> fieldFormat == Boolean-    _ -> False--textMatchesFormat :: FieldFormat -> Text -> Bool-textMatchesFormat fieldFormat value =-  case fieldFormat of-    Rfc3339Utc ->-      hasExtendedUtcShape value-        && isJust (iso8601ParseM (Text.unpack value) :: Maybe UTCTime)-    Date ->-      hasExtendedDateShape value-        && isJust (iso8601ParseM (Text.unpack value) :: Maybe Day)-    Uri -> isJust (parseURI (Text.unpack value))-    UriWithScheme expectedScheme ->-      case parseURI (Text.unpack value) of-        Just parsed ->-          Text.toCaseFold (Text.dropWhileEnd (== ':') (Text.pack (uriScheme parsed)))-            == Text.toCaseFold expectedScheme-        Nothing -> False-    DocumentHandle expectedPrefix ->-      case parseDocumentId value of-        Just documentId -> documentId ^. #prefix == expectedPrefix-        Nothing -> False-    -- Specification §7 defines exactly three actor shapes, and-    -- 'Actor.parseActor' classifies them, so the format is a case match on its-    -- result rather than a second parser. A value the convention does not-    -- define — the specification's own illustrative @team:ga4-docs@ among them —-    -- is 'Actor.UnclassifiedActor' and is reported.-    Actor ->-      case Actor.parseActor value of-        Actor.UnclassifiedActor _ -> False-        _ -> True-    HumanActor -> Actor.isHumanActor (Actor.parseActor value)-    -- A numeric or boolean format never matches text. A @usage_count: "5000"@-    -- is a quoted string in YAML and is reported rather than coerced, which is-    -- the whole point of being able to declare the format.-    Integer -> False-    NonNegativeInteger -> False-    Boolean -> False---- | Whether a YAML number satisfies a numeric format. Uses aeson's own--- 'Integer' decoder, which already rejects a non-integral number, rather than--- reaching for @scientific@: that package is a dependency of @aeson@ but not of--- @okf-core@, so it is importable in a scratch experiment and not from here.--- 'Okf.Document.objectInteger' takes the same route.-numberMatchesFormat :: FieldFormat -> Value -> Bool-numberMatchesFormat fieldFormat actual =-  case Aeson.fromJSON actual :: Aeson.Result Integer of-    Aeson.Error _ -> False-    Aeson.Success parsed ->-      case fieldFormat of-        Integer -> True-        NonNegativeInteger -> parsed >= 0-        _ -> False--hasExtendedDateShape :: Text -> Bool-hasExtendedDateShape value =-  Text.length value == 10-    && Text.index value 4 == '-'-    && Text.index value 7 == '-'--hasExtendedUtcShape :: Text -> Bool-hasExtendedUtcShape value =-  Text.length value >= 20-    && Text.index value 4 == '-'-    && Text.index value 7 == '-'-    && Text.index value 10 == 'T'-    && Text.index value 13 == ':'-    && Text.index value 16 == ':'-    && Text.last value == 'Z'--data FieldValueEvaluation-  = FieldAbsent (Maybe Value)-  | FieldPresent Value-  | FieldWrongShape Value---- | Decide whether a frontmatter value counts as present for one rule. Takes the--- whole rule rather than just its cardinality because the 'Any' case has to know--- whether the rule declares object members: a rule accepting both spellings of--- the OKF v0.2 @verified@ key stays at 'Any' cardinality and must still count a--- mapping as present.------ This is the single point at which okf decides presence, so a change here--- affects every profile check.-evaluateFieldValue :: EffectiveFieldRule -> Maybe Value -> FieldValueEvaluation-evaluateFieldValue _ Nothing = FieldAbsent Nothing-evaluateFieldValue rule (Just actual) =-  case rule ^. #cardinality of-    Any-      | legacyValueIsPresent actual -> FieldPresent actual-      -- A rule that also accepts a mapping counts a non-empty one as present.-      -- Without this a profile declaring both shapes would report `verified`-      -- missing on a document that writes it as a bare mapping.-      | isJust (rule ^. #objectFields), nonEmptyObject actual -> FieldPresent actual-      | otherwise -> FieldAbsent (Just actual)-    Scalar ->-      case actual of-        String value-          | Text.null (Text.strip value) -> FieldAbsent (Just actual)-          | otherwise -> FieldPresent actual-        Number _ -> FieldPresent actual-        Bool _ -> FieldPresent actual-        _ -> FieldWrongShape actual-    List ->-      case actual of-        Array values-          | null values -> FieldAbsent (Just actual)-          | otherwise -> FieldPresent actual-        _ -> FieldWrongShape actual-    Object-      -- An empty mapping is treated as absent for the same reason an empty list-      -- is: a key written with no content is the author saying nothing, and-      -- reporting it missing is more useful than reporting it present and empty.-      | nonEmptyObject actual -> FieldPresent actual-      | isObject actual -> FieldAbsent (Just actual)-      | otherwise -> FieldWrongShape actual--isObject :: Value -> Bool-isObject = \case-  Aeson.Object _ -> True-  _ -> False--nonEmptyObject :: Value -> Bool-nonEmptyObject = \case-  Aeson.Object members -> not (Aeson.KeyMap.null members)-  _ -> False--legacyValueIsPresent :: Value -> Bool-legacyValueIsPresent = \case-  String value -> not (Text.null (Text.strip value))-  Array values -> not (null values)-  _ -> False---- | Check a profile-declared document ID for one concept.-checkDocumentId :: ProfileSpec -> ConceptId -> Text -> TypeRule -> Concept -> [ProfileViolation]-checkDocumentId spec cid ctype rule concept =-  case (spec ^. #idField, rule ^. #idPrefix) of-    (Just fieldName, Just expectedPrefix) ->-      case frontmatterLookup fieldName (conceptFrontmatter concept) of-        Just (String value)-          | not (Text.null (Text.strip value)) ->-              case parseDocumentId value of-                Just documentId-                  | documentId ^. #prefix == expectedPrefix -> []-                _ -> [MalformedDocumentId cid expectedPrefix value]-        _ -> [MissingDocumentId cid ctype expectedPrefix]-    _ -> []---- | Check every non-empty value under the profile's ID field for bundle-wide--- uniqueness. Concept IDs are sorted before grouping so output is deterministic.-checkDuplicateDocumentIds :: ProfileSpec -> [Concept] -> [ProfileViolation]-checkDuplicateDocumentIds spec concepts =-  case spec ^. #idField of-    Nothing -> []-    Just fieldName ->-      concatMap duplicateViolations (groupedHandles fieldName)-  where-    groupedHandles fieldName =-      List.groupBy-        (\(leftHandle, _) (rightHandle, _) -> leftHandle == rightHandle)-        (handles fieldName)-    handles fieldName =-      List.sortOn-        (\(handle, cid) -> (handle, renderConceptId cid))-        [ (handle, conceptIdOf concept)-        | concept <- concepts,-          Just (String handle) <- [frontmatterLookup fieldName (conceptFrontmatter concept)],-          not (Text.null (Text.strip handle))-        ]-    duplicateViolations ((handle, firstConcept) : duplicates) =-      [ DuplicateDocumentId handle firstConcept duplicateConcept-      | (_, duplicateConcept) <- duplicates-      ]-    duplicateViolations [] = []---- | Project a concept's frontmatter (the document's @frontmatter@ field).-conceptFrontmatter :: Concept -> Frontmatter-conceptFrontmatter concept = conceptDocument concept ^. #frontmatter---- | A type rule's @pathPattern@, when present, constrains where the concept's--- file may live.-checkPath :: ConceptId -> Text -> TypeRule -> [ProfileViolation]-checkPath cid ctype rule =-  case rule ^. #pathPattern of-    Nothing -> []-    Just patternText-      | matchPathPattern patternText cid -> []-      | otherwise -> [PathPatternMismatch cid ctype patternText]---- | Match a concept ID against a segment-glob pattern. @*@ matches exactly one--- segment; a single trailing @**@ matches one or more remaining segments; every--- other segment matches literally. Both segment lists must be consumed exactly,--- except for the trailing @**@ case.-matchPathPattern :: Text -> ConceptId -> Bool-matchPathPattern patternText cid =-  go (Text.splitOn "/" patternText) (Text.splitOn "/" (renderConceptId cid))-  where-    go [] [] = True-    go ["**"] (_ : _) = True-    go ("*" : ps) (_ : ss) = go ps ss-    go (p : ps) (s : ss) = p == s && go ps ss-    go _ _ = False---- | A type rule's @resourceScheme@, when present, requires a @resource:@ value--- whose scheme matches.-checkResource :: ConceptId -> Text -> TypeRule -> Concept -> [ProfileViolation]-checkResource cid ctype rule concept =-  case rule ^. #resourceScheme of-    Nothing -> []-    Just scheme ->-      case conceptResource concept of-        Nothing -> [MissingResource cid ctype scheme]-        Just value-          | (scheme <> "://") `Text.isPrefixOf` value -> []-          | otherwise -> [ResourceSchemeMismatch cid scheme value]---- | A type rule's @# Schema@ contract: when @requireSchemaSection@ is set, the--- body must contain a @# Schema@ section whose table header begins with the--- required @schemaColumns@ (case-insensitive, trimmed, compared as a prefix so a--- team may add trailing columns without tripping the check).-checkSchema :: ConceptId -> Text -> TypeRule -> Concept -> [ProfileViolation]-checkSchema cid ctype rule concept-  | not (rule ^. #requireSchemaSection) = []-  | otherwise =-      case schemaSectionColumns (conceptDocument concept ^. #body) of-        Nothing -> [MissingSchemaSection cid ctype]-        Just actual ->-          let expected = rule ^. #schemaColumns-              norm = map (Text.toLower . Text.strip)-           in [ SchemaColumnsMismatch cid ctype expected actual-              | not (norm expected `List.isPrefixOf` norm actual)-              ]---- | The header-row columns of the first GitHub-flavored table that follows the--- first top-level @# Schema@ heading, or 'Nothing' if there is no Schema heading--- or no following table. Columns are trimmed.-schemaSectionColumns :: Text -> Maybe [Text]-schemaSectionColumns markdown =-  let CMarkGFM.Node _ _ topLevel = CMarkGFM.commonmarkToNode markdownOptions [CMarkGFM.extTable] markdown-   in firstTableAfterSchema topLevel--firstTableAfterSchema :: [CMarkGFM.Node] -> Maybe [Text]-firstTableAfterSchema topLevel =-  case dropWhile (not . isSchemaHeading) topLevel of-    (_heading : rest) -> headerRow rest-    [] -> Nothing-  where-    isSchemaHeading (CMarkGFM.Node _ (CMarkGFM.HEADING _) inner) =-      Text.toLower (Text.strip (nodeText inner)) == "schema"-    isSchemaHeading _ = False--    headerRow [] = Nothing-    headerRow (CMarkGFM.Node _ (CMarkGFM.TABLE _) tableChildren : _) =-      case tableChildren of-        (CMarkGFM.Node _ CMarkGFM.TABLE_ROW cells : _) -> Just (map cellText cells)-        _ -> Nothing-    headerRow (_ : more) = headerRow more--    cellText (CMarkGFM.Node _ _ inner) = Text.strip (nodeText inner)---- | Concatenate all @TEXT@/@CODE@ literals under a node list, recursively.-nodeText :: [CMarkGFM.Node] -> Text-nodeText = foldMap go-  where-    go (CMarkGFM.Node _ (CMarkGFM.TEXT t) _) = t-    go (CMarkGFM.Node _ (CMarkGFM.CODE t) _) = t-    go (CMarkGFM.Node _ _ inner) = nodeText inner+    ValueSelector (..),+    PresenceConstraint (..),+    TimestampOrderConstraint (..),+    MembershipConstraint (..),+    UniqueValuesConstraint (..),+    EffectiveConceptConstraints,+    conceptPresenceConstraints,+    conceptResolvedSelectors,+    conceptTimestampOrderConstraints,+    conceptMembershipConstraints,+    conceptUniqueValuesConstraints,+    compiledProfileBaseConstraints,+    compiledProfileConstraintsForType,+    fieldRuleElementConstraints,+    fieldRuleObjectConstraints,+    resolveValueSelector,+    renderConceptConstraints,+    renderValueSelector,+    frontmatterConstraints,+    nestedConstraints,+    FrontmatterRules (..),+    FieldCondition (..),+    HandleReferenceRule (..),+    PathReferenceRule (..),+    FieldRule (..),+    NestedRules (..),+    NestedFieldRule (..),+    Cardinality (..),+    FieldFormat (..),+    TypeRule (..),+    FieldPath (..),+    FieldPathSegment (..),+    loadProfileFile,+    decodeProfileExpr,+    profileFieldDescription,+    CompiledProfile,+    ProfileDefinitionError (..),+    compileProfile,+    compiledProfileSpec,+    compiledProfileRequiredBundleVersion,+    profileFieldDescriptionForType,++    -- * Compiled rule inspection++    -- | A read-only window onto what a compiled profile actually demands. The+    -- rule types are abstract on purpose: read them through the accessors below+    -- so that later profile features can extend the compiled encoding without+    -- breaking consumers.+    --+    -- Two encodings are easy to misread and are worth stating up front. An+    -- __empty presence-clause list means the key is optional__, not that it is+    -- unconstrained; and an __empty allowed-value list means unconstrained__,+    -- not that no value is permitted.+    EffectiveFieldRule,+    PresenceClause,+    FieldRequirement (..),+    fieldRulePresenceClauses,+    presenceClauseRequirement,+    presenceClauseCondition,+    fieldRuleDescription,+    fieldRuleAllowedValues,+    fieldRuleCardinality,+    fieldRuleFormat,+    fieldRuleReference,+    fieldRuleUniqueBy,+    fieldRulePath,+    fieldRuleElementFields,+    fieldRuleObjectFields,+    fieldRuleElementAllowsUnknownFields,+    fieldRuleObjectAllowsUnknownFields,+    compiledProfileTypeNames,+    compiledProfileBaseRules,+    compiledProfileRulesForType,+    renderCardinalityName,+    renderFieldFormatName,++    -- * Validation+    DocumentId (..),+    parseDocumentId,+    renderDocumentId,+    documentIdsInBundle,+    nextDocumentId,+    ProfileViolation (..),+    validateProfile,+    validateProfileWith,+    validateProfileVersion,++    -- * Body inspection+    schemaSectionColumns,+  )+where++import CMarkGFM qualified+import Control.Exception (SomeException)+import Data.Aeson (ToJSON (..), object, (.=))+import Data.Aeson qualified as Aeson+import Data.Aeson.Key qualified as Aeson.Key+import Data.Aeson.KeyMap qualified as Aeson.KeyMap+import Data.Char (isAsciiLower, isAsciiUpper)+import Data.Foldable (toList)+import Data.List qualified as List+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (catMaybes, mapMaybe, maybeToList)+import Data.Set qualified as Set+import Data.Text qualified as Text+import Data.Text.Read qualified as Text.Read+import Data.Time.Calendar (Day)+import Data.Time.Clock (UTCTime)+import Data.Time.Format.ISO8601 (iso8601ParseM)+import Data.Vector qualified as Vector+import Data.Void (Void)+import Dhall (FromDhall (..), auto, genericAutoWith)+import Dhall qualified+import Dhall.Core (Expr)+import Dhall.Core qualified as Dhall.Core+import Dhall.Map qualified as Dhall.Map+import Dhall.Src (Src)+import Network.URI (parseURI, uriScheme)+import Numeric.Natural (Natural)+import Okf.Exception (catchSynchronous)++-- Imported qualified: 'Okf.Actor.HumanActor' is a constructor of 'Actor.Actor'+-- and 'HumanActor' is a constructor of 'FieldFormat', so an unqualified import+-- makes the two ambiguous.+import Okf.Actor qualified as Actor+import Okf.Bundle+  ( BundleInventory,+    Concept,+    bundleInventoryMember,+    bundleInventoryOfConcepts,+    conceptDocument,+    conceptIdOf,+    conceptResource,+    conceptType,+  )+import Okf.ConceptId (ConceptId, conceptIdFromFilePath, renderConceptId)+import Okf.Document+  ( Frontmatter,+    coreFrontmatterFields,+    fieldsSupersededInV02,+    frontmatterKeys,+    frontmatterLookup,+  )+import Okf.Index+  ( OkfVersion (..),+    VersionDeclaration (..),+    parseOkfVersion,+    renderOkfVersion,+    supportedOkfVersion,+  )+import Okf.Markdown (markdownOptions)+import Okf.Path (PathReference (..), classifyPathReference)++-- 'List' and 'Object' are 'Cardinality' constructors here; the names aeson uses+-- for the corresponding 'Value' constructors are reached as 'Aeson.Array' and+-- 'Aeson.Object'.+import Okf.Prelude hiding (List, Object, (.=))+import Okf.Validation (ValidationProfile (..))+import System.FilePath qualified as FilePath+import Text.Regex.TDFA (Regex, defaultCompOpt, defaultExecOpt)+import Text.Regex.TDFA.Text qualified as Regex.Text+import "generic-lens" Data.Generics.Labels ()++-- | A complete house profile. @description@ concisely documents the profile's+-- identity. @guidance@ is multiline Markdown prescribing how authors should do+-- the work. Neither is checked against a bundle or executed, and neither can+-- produce a 'ProfileViolation'.+--+-- @requireBundleVersion@ and @okfVersion@ are easy to confuse and answer+-- different questions. @okfVersion@ says which version's rules /this profile+-- writes/, and 'compileProfile' checks the profile's own rules against it.+-- @requireBundleVersion@ says what the profile demands of a /bundle/: @Just+-- \"0.2\"@ means the bundle's root @index.md@ must declare @okf_version@ at 0.2+-- or later, checked by 'validateProfileVersion'. Neither constrains the other.+data ProfileSpec = ProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    guidance :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !FrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    requireBundleVersion :: !(Maybe Text),+    types :: ![TypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | Frontmatter keys the profile expects on every concept. @required@ is always+-- checked, @recommended@ only under 'StrictAuthoring', and @optional@ never:+-- an optional key is fully validated whenever it is present and its absence is+-- never a deviation in any mode.+data FrontmatterRules = FrontmatterRules+  { required :: ![FieldRule],+    recommended :: ![FieldRule],+    optional :: ![FieldRule],+    presenceConstraints :: ![PresenceConstraint],+    timestampOrderConstraints :: ![TimestampOrderConstraint],+    membershipConstraints :: ![MembershipConstraint],+    uniqueValuesConstraints :: ![UniqueValuesConstraint]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | A same-scope predicate controlling whether a field's presence rule applies.+-- The source field must compile to a closed scalar textual vocabulary.+data FieldCondition = FieldCondition+  { field :: !Text,+    hasValue :: ![Text]+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++-- | A top-level field whose textual values point either to a local document+-- handle with one prefix or to an absolute URI with an explicitly allowed+-- scheme. External targets are never resolved by okf.+data HandleReferenceRule = HandleReferenceRule+  { localPrefix :: !Text,+    externalUriSchemes :: ![Text],+    allowSelf :: !Bool,+    allowLocal :: !Bool,+    externalUriPattern :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++-- | A field whose values name a path or URI per OKF v0.2 specification §6.2: an+-- absolute URL, a bundle-relative path beginning with @\/@, or an ordinary+-- relative path resolved against the concept's own directory.+--+-- Deliberately distinct from 'HandleReferenceRule'. A handle resolves against+-- the bundle's document-ID index and fails by carrying the wrong prefix or+-- having no owner; a path resolves against the concept tree and fails by not+-- being a §6.2 shape, by climbing above the bundle root, or by naming a concept+-- that is not there. Declaring both on one rule is a definition error.+--+-- An empty @externalUriSchemes@ means no absolute URL is permitted at all, so a+-- separate "must be a path, never a URL" flag would say nothing new. Which+-- bundle paths okf can resolve depends on the entry point: 'validateProfileWith'+-- resolves every file the bundle holds, including §6.3's+-- @references\/attesters\/revenue.py@, while 'validateProfile' is handed+-- concepts alone and so resolves @.md@ targets only.+data PathReferenceRule = PathReferenceRule+  { externalUriSchemes :: ![Text],+    allowSelf :: !Bool+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++-- | One documented frontmatter key. The description is prose for humans and is+-- never checked against a bundle.+--+-- @elementFields@ and @objectFields@ describe two different shapes.+-- @elementFields@ constrains the record inside /each element of a list/;+-- @objectFields@ constrains the record that /is/ the value. Declaring both means+-- either spelling is accepted and both are checked against the same member+-- rules, which is how a profile describes the OKF v0.2 @verified@ key.+data FieldRule = FieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe FieldFormat),+    elementFields :: !(Maybe NestedRules),+    objectFields :: !(Maybe NestedRules),+    reference :: !(Maybe HandleReferenceRule),+    path :: !(Maybe PathReferenceRule),+    when :: !(Maybe FieldCondition),+    uniqueBy :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | Rules for the flat object stored in each element of a list-valued field, or+-- in the mapping that is the value of an object-valued field. The nested rule+-- type has neither an @elementFields@ nor an @objectFields@ member, which makes+-- the public descriptor depth-bounded rather than recursive.+data NestedRules = NestedRules+  { allowUnknownFields :: !Bool,+    required :: ![NestedFieldRule],+    recommended :: ![NestedFieldRule],+    optional :: ![NestedFieldRule],+    presenceConstraints :: ![PresenceConstraint],+    timestampOrderConstraints :: ![TimestampOrderConstraint]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | One field inside a list element record or an object-valued mapping. It+-- carries @path@ because @sources[].resource@ is the motivating path-valued+-- field of §6.2 and lives inside a list element; it deliberately carries no+-- @reference@, because no v0.2 field names a document handle at nested scope.+data NestedFieldRule = NestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe FieldFormat),+    path :: !(Maybe PathReferenceRule),+    when :: !(Maybe FieldCondition),+    reference :: !(Maybe HandleReferenceRule)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | Whether a key must be a single value, a non-empty list, a mapping, or any+-- of them. 'Object' is placed last so the derived 'Ord' keeps the relative+-- order of the three published alternatives, which the definition-error sort key+-- relies on.+data Cardinality = Any | Scalar | List | Object+  deriving stock (Generic, Eq, Ord, Show)++-- | Decoded from the three-alternative published union in+-- @okf-core\/dhall\/Cardinality.dhall@. 'Object' is deliberately unreachable+-- from Dhall: it is produced only by compilation, when a rule declares+-- @objectFields@. Adding an alternative to the published union would change the+-- type of every value written against it and would break descriptors pinned to+-- the previous schema, which no record-level fallback decoder can repair,+-- because every frozen generation in the chain refers to this same type. An+-- author who wants to say "this key must be a mapping" and nothing more writes+-- @objectFields = Some NestedRules::{=}@.+instance FromDhall Cardinality where+  autoWith _normalizer =+    Dhall.union+      ( (Any <$ Dhall.constructor "Any" Dhall.unit)+          <> (Scalar <$ Dhall.constructor "Scalar" Dhall.unit)+          <> (List <$ Dhall.constructor "List" Dhall.unit)+      )++-- | A named value format. Formats constrain present values but do not imply+-- that a field must be present.+--+-- The first five constrain text. 'Actor' and 'HumanActor' constrain text against+-- the OKF v0.2 actor convention of specification §7, classified by+-- 'Okf.Actor.parseActor'. 'Integer', 'NonNegativeInteger', and 'Boolean'+-- constrain a value that is not text at all; declaring one of them refines an+-- unspecified cardinality to 'Scalar', because otherwise a numeric or boolean+-- key is reported missing before its value is ever examined.+--+-- The OKF v0.2 alternatives are appended after 'DocumentHandle' so the derived+-- 'Ord' keeps the relative order of the original five, which the+-- definition-error sort key relies on.+data FieldFormat+  = Rfc3339Utc+  | Date+  | Uri+  | UriWithScheme Text+  | DocumentHandle Text+  | Actor+  | HumanActor+  | Integer+  | NonNegativeInteger+  | Boolean+  | FiniteDecimal+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++-- | One rule per allowed concept @type@ string. @guidance@ adds authoring+-- procedure specific to this type; it is documentary and never executed.+data TypeRule = TypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    guidance :: !(Maybe Text),+    frontmatter :: !FrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++-- | Decode @type_@ from the Dhall field @type@ by stripping the trailing+-- underscore; all other fields map by their exact name. (Mirrors how+-- 'Okf.Bundle' uses a @type_@ field to avoid clashing with the @type@ keyword.)+instance FromDhall TypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | Encode a profile so tooling can consume the same descriptor okf reads.+-- Written by hand rather than derived so the key order is stable and, more+-- importantly, so 'TypeRule' emits @type@ rather than the Haskell field name+-- @type_@ — matching the Dhall field and how 'Okf.Graph.Node' already encodes.+instance ToJSON ProfileSpec where+  toJSON ProfileSpec {name, description, guidance, okfVersion, frontmatter, allowUnknownTypes, allowUnknownFields, idField, requireBundleVersion, types = typeRules} =+    object+      [ "name" .= name,+        "description" .= description,+        "guidance" .= guidance,+        "okfVersion" .= okfVersion,+        "requireBundleVersion" .= requireBundleVersion,+        "allowUnknownTypes" .= allowUnknownTypes,+        "allowUnknownFields" .= allowUnknownFields,+        "idField" .= idField,+        "frontmatter" .= frontmatter,+        "types" .= typeRules+      ]++instance ToJSON FrontmatterRules where+  toJSON FrontmatterRules {required, recommended, optional, presenceConstraints, timestampOrderConstraints, membershipConstraints, uniqueValuesConstraints} =+    object+      [ "required" .= required,+        "recommended" .= recommended,+        "optional" .= optional,+        "presenceConstraints" .= presenceConstraints,+        "timestampOrderConstraints" .= timestampOrderConstraints,+        "membershipConstraints" .= membershipConstraints,+        "uniqueValuesConstraints" .= uniqueValuesConstraints+      ]++instance ToJSON FieldCondition where+  toJSON FieldCondition {field = fieldName, hasValue} =+    object+      [ "field" .= fieldName,+        "hasValue" .= hasValue+      ]++instance ToJSON HandleReferenceRule where+  toJSON HandleReferenceRule {localPrefix, externalUriSchemes, allowSelf, allowLocal, externalUriPattern} =+    object+      [ "localPrefix" .= localPrefix,+        "externalUriSchemes" .= externalUriSchemes,+        "allowSelf" .= allowSelf,+        "allowLocal" .= allowLocal,+        "externalUriPattern" .= externalUriPattern+      ]++instance ToJSON PathReferenceRule where+  toJSON PathReferenceRule {externalUriSchemes, allowSelf} =+    object+      [ "externalUriSchemes" .= externalUriSchemes,+        "allowSelf" .= allowSelf+      ]++instance ToJSON FieldRule where+  toJSON FieldRule {field = fieldName, description, allowedValues, cardinality, format, elementFields, objectFields, reference, path = pathRule, when = condition, uniqueBy} =+    object+      [ "field" .= fieldName,+        "description" .= description,+        "allowedValues" .= allowedValues,+        "cardinality" .= cardinality,+        "format" .= format,+        "elementFields" .= elementFields,+        "reference" .= reference,+        "when" .= condition,+        -- Appended rather than placed beside @elementFields@, so that the list+        -- reads as "the keys this instance has always emitted, then the ones+        -- added since". A consumer keys on names, not position.+        "objectFields" .= objectFields,+        "path" .= pathRule,+        "uniqueBy" .= uniqueBy+      ]++instance ToJSON NestedRules where+  toJSON NestedRules {required, recommended, optional, presenceConstraints, timestampOrderConstraints, allowUnknownFields} =+    object+      [ "allowUnknownFields" .= allowUnknownFields,+        "required" .= required,+        "recommended" .= recommended,+        "optional" .= optional,+        "presenceConstraints" .= presenceConstraints,+        "timestampOrderConstraints" .= timestampOrderConstraints+      ]++instance ToJSON NestedFieldRule where+  toJSON NestedFieldRule {field = fieldName, description, allowedValues, cardinality, format, path = pathRule, when = condition, reference} =+    object+      [ "field" .= fieldName,+        "description" .= description,+        "allowedValues" .= allowedValues,+        "cardinality" .= cardinality,+        "format" .= format,+        "when" .= condition,+        -- Appended for the same reason 'FieldRule' appends @objectFields@.+        "path" .= pathRule,+        "reference" .= reference+      ]++instance ToJSON Cardinality where+  toJSON = String . cardinalityName++cardinalityName :: Cardinality -> Text+cardinalityName = \case+  Any -> "any"+  Scalar -> "scalar"+  List -> "list"+  Object -> "object"++instance ToJSON FieldFormat where+  toJSON = \case+    Rfc3339Utc -> String "rfc3339-utc"+    Date -> String "date"+    Uri -> String "uri"+    UriWithScheme scheme -> object ["uriWithScheme" .= scheme]+    DocumentHandle prefix -> object ["documentHandle" .= prefix]+    Actor -> String "actor"+    HumanActor -> String "human-actor"+    Integer -> String "integer"+    NonNegativeInteger -> String "non-negative-integer"+    FiniteDecimal -> String "finite-decimal"+    Boolean -> String "boolean"++instance ToJSON TypeRule where+  toJSON+    TypeRule+      { type_ = ruleType,+        description,+        guidance,+        frontmatter,+        pathPattern,+        resourceScheme,+        requireSchemaSection,+        schemaColumns,+        idPrefix+      } =+      object+        [ "type" .= ruleType,+          "description" .= description,+          "guidance" .= guidance,+          "frontmatter" .= frontmatter,+          "pathPattern" .= pathPattern,+          "resourceScheme" .= resourceScheme,+          "requireSchemaSection" .= requireSchemaSection,+          "schemaColumns" .= schemaColumns,+          "idPrefix" .= idPrefix+        ]++-- | The complete descriptor generation published by okf-core 0.8.0.0, frozen+-- immediately before profile and type guidance were added. Every reachable+-- record and union is copied here so future schema additions cannot change the+-- Dhall type this decoder accepts. Exercised by+-- @okf-core/test/fixtures/profiles/pre-guidance-0.8.0.0.dhall@.+data PreGuidanceCardinality+  = PreGuidanceAny+  | PreGuidanceScalar+  | PreGuidanceList+  deriving stock (Generic, Eq, Ord, Show)++instance FromDhall PreGuidanceCardinality where+  autoWith _normalizer =+    Dhall.union+      ( (PreGuidanceAny <$ Dhall.constructor "Any" Dhall.unit)+          <> (PreGuidanceScalar <$ Dhall.constructor "Scalar" Dhall.unit)+          <> (PreGuidanceList <$ Dhall.constructor "List" Dhall.unit)+      )++data PreGuidanceFieldFormat+  = PreGuidanceRfc3339Utc+  | PreGuidanceDate+  | PreGuidanceUri+  | PreGuidanceUriWithScheme Text+  | PreGuidanceDocumentHandle Text+  | PreGuidanceActor+  | PreGuidanceHumanActor+  | PreGuidanceInteger+  | PreGuidanceNonNegativeInteger+  | PreGuidanceBoolean+  deriving stock (Generic, Eq, Ord, Show)++instance FromDhall PreGuidanceFieldFormat where+  autoWith _normalizer =+    Dhall.union+      ( (PreGuidanceRfc3339Utc <$ Dhall.constructor "Rfc3339Utc" Dhall.unit)+          <> (PreGuidanceDate <$ Dhall.constructor "Date" Dhall.unit)+          <> (PreGuidanceUri <$ Dhall.constructor "Uri" Dhall.unit)+          <> (PreGuidanceUriWithScheme <$> Dhall.constructor "UriWithScheme" Dhall.auto)+          <> (PreGuidanceDocumentHandle <$> Dhall.constructor "DocumentHandle" Dhall.auto)+          <> (PreGuidanceActor <$ Dhall.constructor "Actor" Dhall.unit)+          <> (PreGuidanceHumanActor <$ Dhall.constructor "HumanActor" Dhall.unit)+          <> (PreGuidanceInteger <$ Dhall.constructor "Integer" Dhall.unit)+          <> (PreGuidanceNonNegativeInteger <$ Dhall.constructor "NonNegativeInteger" Dhall.unit)+          <> (PreGuidanceBoolean <$ Dhall.constructor "Boolean" Dhall.unit)+      )++data PreGuidanceFieldCondition = PreGuidanceFieldCondition+  { field :: !Text,+    hasValue :: ![Text]+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++data PreGuidanceHandleReferenceRule = PreGuidanceHandleReferenceRule+  { localPrefix :: !Text,+    externalUriSchemes :: ![Text],+    allowSelf :: !Bool,+    allowLocal :: !Bool,+    externalUriPattern :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++data PreGuidancePathReferenceRule = PreGuidancePathReferenceRule+  { externalUriSchemes :: ![Text],+    allowSelf :: !Bool+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++-- | FROZEN: complete descriptor at cfecb72e543c28f5a77ff852445fdd0f256b8810,+-- after product-discovery constraints and before nested closure. No live+-- descriptor records or unions are shared with this generation.+data PreNestedClosureCardinality+  = PreNestedClosureAny+  | PreNestedClosureScalar+  | PreNestedClosureList+  deriving stock (Generic, Eq, Ord, Show)++instance FromDhall PreNestedClosureCardinality where+  autoWith _normalizer =+    Dhall.union+      ( (PreNestedClosureAny <$ Dhall.constructor "Any" Dhall.unit)+          <> (PreNestedClosureScalar <$ Dhall.constructor "Scalar" Dhall.unit)+          <> (PreNestedClosureList <$ Dhall.constructor "List" Dhall.unit)+      )++data PreNestedClosureFieldFormat+  = PreNestedClosureRfc3339Utc+  | PreNestedClosureDate+  | PreNestedClosureUri+  | PreNestedClosureUriWithScheme Text+  | PreNestedClosureDocumentHandle Text+  | PreNestedClosureActor+  | PreNestedClosureHumanActor+  | PreNestedClosureInteger+  | PreNestedClosureNonNegativeInteger+  | PreNestedClosureFiniteDecimal+  | PreNestedClosureBoolean+  deriving stock (Generic, Eq, Ord, Show)++instance FromDhall PreNestedClosureFieldFormat where+  autoWith _normalizer =+    Dhall.union+      ( (PreNestedClosureRfc3339Utc <$ Dhall.constructor "Rfc3339Utc" Dhall.unit)+          <> (PreNestedClosureDate <$ Dhall.constructor "Date" Dhall.unit)+          <> (PreNestedClosureUri <$ Dhall.constructor "Uri" Dhall.unit)+          <> (PreNestedClosureUriWithScheme <$> Dhall.constructor "UriWithScheme" Dhall.auto)+          <> (PreNestedClosureDocumentHandle <$> Dhall.constructor "DocumentHandle" Dhall.auto)+          <> (PreNestedClosureActor <$ Dhall.constructor "Actor" Dhall.unit)+          <> (PreNestedClosureHumanActor <$ Dhall.constructor "HumanActor" Dhall.unit)+          <> (PreNestedClosureInteger <$ Dhall.constructor "Integer" Dhall.unit)+          <> (PreNestedClosureNonNegativeInteger <$ Dhall.constructor "NonNegativeInteger" Dhall.unit)+          <> (PreNestedClosureFiniteDecimal <$ Dhall.constructor "FiniteDecimal" Dhall.unit)+          <> (PreNestedClosureBoolean <$ Dhall.constructor "Boolean" Dhall.unit)+      )++data PreNestedClosureProfileSpec = PreNestedClosureProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    guidance :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !PreNestedClosureFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    requireBundleVersion :: !(Maybe Text),+    types :: ![PreNestedClosureTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreNestedClosureTypeRule = PreNestedClosureTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    guidance :: !(Maybe Text),+    frontmatter :: !PreNestedClosureFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall PreNestedClosureTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++data PreNestedClosureFrontmatterRules = PreNestedClosureFrontmatterRules+  { required :: ![PreNestedClosureFieldRule],+    recommended :: ![PreNestedClosureFieldRule],+    optional :: ![PreNestedClosureFieldRule],+    presenceConstraints :: ![PreNestedClosurePresenceConstraint],+    timestampOrderConstraints :: ![PreNestedClosureTimestampOrderConstraint],+    membershipConstraints :: ![PreNestedClosureMembershipConstraint],+    uniqueValuesConstraints :: ![PreNestedClosureUniqueValuesConstraint]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreNestedClosureFieldRule = PreNestedClosureFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !PreNestedClosureCardinality,+    format :: !(Maybe PreNestedClosureFieldFormat),+    elementFields :: !(Maybe PreNestedClosureNestedRules),+    objectFields :: !(Maybe PreNestedClosureNestedRules),+    reference :: !(Maybe PreNestedClosureHandleReferenceRule),+    path :: !(Maybe PreNestedClosurePathReferenceRule),+    when :: !(Maybe PreNestedClosureFieldCondition),+    uniqueBy :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreNestedClosureNestedRules = PreNestedClosureNestedRules+  { required :: ![PreNestedClosureNestedFieldRule],+    recommended :: ![PreNestedClosureNestedFieldRule],+    optional :: ![PreNestedClosureNestedFieldRule],+    presenceConstraints :: ![PreNestedClosurePresenceConstraint],+    timestampOrderConstraints :: ![PreNestedClosureTimestampOrderConstraint]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreNestedClosureNestedFieldRule = PreNestedClosureNestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !PreNestedClosureCardinality,+    format :: !(Maybe PreNestedClosureFieldFormat),+    path :: !(Maybe PreNestedClosurePathReferenceRule),+    when :: !(Maybe PreNestedClosureFieldCondition),+    reference :: !(Maybe PreNestedClosureHandleReferenceRule)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreNestedClosureFieldCondition = PreNestedClosureFieldCondition+  { field :: !Text,+    hasValue :: ![Text]+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++data PreNestedClosureHandleReferenceRule = PreNestedClosureHandleReferenceRule+  { localPrefix :: !Text,+    externalUriSchemes :: ![Text],+    allowSelf :: !Bool,+    allowLocal :: !Bool,+    externalUriPattern :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++data PreNestedClosurePathReferenceRule = PreNestedClosurePathReferenceRule+  { externalUriSchemes :: ![Text],+    allowSelf :: !Bool+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++data PreNestedClosureValueSelector = PreNestedClosureValueSelector {field :: !Text, member :: !(Maybe Text)}+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++data PreNestedClosurePresenceConstraint = PreNestedClosurePresenceConstraint+  { when :: !(Maybe PreNestedClosureFieldCondition),+    whenAnyPresent :: ![PreNestedClosureValueSelector],+    requireAll :: ![PreNestedClosureValueSelector],+    requireAny :: ![PreNestedClosureValueSelector]+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++data PreNestedClosureTimestampOrderConstraint = PreNestedClosureTimestampOrderConstraint {before :: !Text, after :: !Text}+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++data PreNestedClosureMembershipConstraint = PreNestedClosureMembershipConstraint {source :: !PreNestedClosureValueSelector, target :: !PreNestedClosureValueSelector}+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++newtype PreNestedClosureUniqueValuesConstraint = PreNestedClosureUniqueValuesConstraint {selectors :: [PreNestedClosureValueSelector]}+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++-- | FROZEN: complete public 0.10.0.0 generation, before concept constraints+-- and FiniteDecimal. Only unions and policies already frozen above are shared.+data PreProductDiscoveryFieldRule = PreProductDiscoveryFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !PreGuidanceCardinality,+    format :: !(Maybe PreGuidanceFieldFormat),+    elementFields :: !(Maybe PreProductDiscoveryNestedRules),+    objectFields :: !(Maybe PreProductDiscoveryNestedRules),+    reference :: !(Maybe PreGuidanceHandleReferenceRule),+    path :: !(Maybe PreGuidancePathReferenceRule),+    when :: !(Maybe PreGuidanceFieldCondition),+    uniqueBy :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreProductDiscoveryNestedRules = PreProductDiscoveryNestedRules+  { required :: ![PreProductDiscoveryNestedFieldRule],+    recommended :: ![PreProductDiscoveryNestedFieldRule],+    optional :: ![PreProductDiscoveryNestedFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreProductDiscoveryNestedFieldRule = PreProductDiscoveryNestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !PreGuidanceCardinality,+    format :: !(Maybe PreGuidanceFieldFormat),+    path :: !(Maybe PreGuidancePathReferenceRule),+    when :: !(Maybe PreGuidanceFieldCondition),+    reference :: !(Maybe PreGuidanceHandleReferenceRule)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreProductDiscoveryFrontmatterRules = PreProductDiscoveryFrontmatterRules+  { required :: ![PreProductDiscoveryFieldRule],+    recommended :: ![PreProductDiscoveryFieldRule],+    optional :: ![PreProductDiscoveryFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreProductDiscoveryTypeRule = PreProductDiscoveryTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    guidance :: !(Maybe Text),+    frontmatter :: !PreProductDiscoveryFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall PreProductDiscoveryTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++data PreProductDiscoveryProfileSpec = PreProductDiscoveryProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    guidance :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !PreProductDiscoveryFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    requireBundleVersion :: !(Maybe Text),+    types :: ![PreProductDiscoveryTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreGuidanceFieldRule = PreGuidanceFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !PreGuidanceCardinality,+    format :: !(Maybe PreGuidanceFieldFormat),+    elementFields :: !(Maybe PreGuidanceNestedRules),+    objectFields :: !(Maybe PreGuidanceNestedRules),+    reference :: !(Maybe PreGuidanceHandleReferenceRule),+    path :: !(Maybe PreGuidancePathReferenceRule),+    when :: !(Maybe PreGuidanceFieldCondition),+    uniqueBy :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreGuidanceNestedRules = PreGuidanceNestedRules+  { required :: ![PreGuidanceNestedFieldRule],+    recommended :: ![PreGuidanceNestedFieldRule],+    optional :: ![PreGuidanceNestedFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreGuidanceNestedFieldRule = PreGuidanceNestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !PreGuidanceCardinality,+    format :: !(Maybe PreGuidanceFieldFormat),+    path :: !(Maybe PreGuidancePathReferenceRule),+    when :: !(Maybe PreGuidanceFieldCondition),+    reference :: !(Maybe PreGuidanceHandleReferenceRule)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreGuidanceFrontmatterRules = PreGuidanceFrontmatterRules+  { required :: ![PreGuidanceFieldRule],+    recommended :: ![PreGuidanceFieldRule],+    optional :: ![PreGuidanceFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreGuidanceTypeRule = PreGuidanceTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !PreGuidanceFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall PreGuidanceTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++data PreGuidanceProfileSpec = PreGuidanceProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !PreGuidanceFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    requireBundleVersion :: !(Maybe Text),+    types :: ![PreGuidanceTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | The okf 0.2.x profile record: frontmatter keys were bare strings and+-- nothing carried a description. Decoded only as a fallback, so descriptors+-- written before descriptions existed keep loading unchanged. Deliberately+-- private and deliberately frozen — it is a record of a retired shape, not a+-- second profile model. Exercised by+-- @okf-core\/test\/fixtures\/profiles\/legacy-0.2.dhall@.+data LegacyProfileSpec = LegacyProfileSpec+  { name :: !Text,+    okfVersion :: !Text,+    frontmatter :: !LegacyFrontmatterRules,+    allowUnknownTypes :: !Bool,+    idField :: !(Maybe Text),+    types :: ![LegacyTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | The okf 0.2.x frontmatter record: two lists of bare key names.+data LegacyFrontmatterRules = LegacyFrontmatterRules+  { required :: ![Text],+    recommended :: ![Text]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | The okf 0.2.x per-@type@ rule: today's 'TypeRule' without descriptions or+-- type-specific frontmatter.+data LegacyTypeRule = LegacyTypeRule+  { type_ :: !Text,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall LegacyTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The five-alternative published format union, frozen before the OKF v0.2+-- value formats were added.+--+-- Unlike every other frozen shape below this is a /union/ rather than a record.+-- A Dhall union value carries its full alternative set in its type, so a+-- descriptor pinned to the five-alternative+-- @okf-core\/dhall\/FieldFormat.dhall@ does not typecheck against the current+-- decoder, and no record-level fallback can repair that: every frozen generation+-- would still refer to the widened 'FieldFormat'. Every frozen generation below+-- therefore refers to this type instead.+--+-- The instance is hand-written rather than derived so that the Dhall alternative+-- names stay @Rfc3339Utc@ and friends while the Haskell constructors stay+-- distinct from the current type's.+data PreV02FieldFormat+  = LegacyRfc3339Utc+  | LegacyDate+  | LegacyUri+  | LegacyUriWithScheme Text+  | LegacyDocumentHandle Text+  deriving stock (Generic, Eq, Ord, Show)++instance FromDhall PreV02FieldFormat where+  autoWith _normalizer =+    Dhall.union+      ( (LegacyRfc3339Utc <$ Dhall.constructor "Rfc3339Utc" Dhall.unit)+          <> (LegacyDate <$ Dhall.constructor "Date" Dhall.unit)+          <> (LegacyUri <$ Dhall.constructor "Uri" Dhall.unit)+          <> (LegacyUriWithScheme <$> Dhall.constructor "UriWithScheme" Dhall.auto)+          <> (LegacyDocumentHandle <$> Dhall.constructor "DocumentHandle" Dhall.auto)+      )++upgradePreV02FieldFormat :: PreV02FieldFormat -> FieldFormat+upgradePreV02FieldFormat = \case+  LegacyRfc3339Utc -> Rfc3339Utc+  LegacyDate -> Date+  LegacyUri -> Uri+  LegacyUriWithScheme scheme -> UriWithScheme scheme+  LegacyDocumentHandle prefix -> DocumentHandle prefix++-- | The complete 0.7.0.0 descriptor generation, frozen before nested+-- document-reference policies and record-list uniqueness were added. Every+-- record that directly or transitively contains one of the grown records is+-- copied so a descriptor pinned to 0.7.0.0 remains decodable as one closed+-- Dhall type.+data PreNestedReferenceHandleReferenceRule = PreNestedReferenceHandleReferenceRule+  { localPrefix :: !Text,+    externalUriSchemes :: ![Text],+    allowSelf :: !Bool+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall)++data PreNestedReferenceFieldRule = PreNestedReferenceFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreGuidanceFieldFormat),+    elementFields :: !(Maybe PreNestedReferenceNestedRules),+    objectFields :: !(Maybe PreNestedReferenceNestedRules),+    reference :: !(Maybe PreNestedReferenceHandleReferenceRule),+    path :: !(Maybe PathReferenceRule),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreNestedReferenceNestedRules = PreNestedReferenceNestedRules+  { required :: ![PreNestedReferenceNestedFieldRule],+    recommended :: ![PreNestedReferenceNestedFieldRule],+    optional :: ![PreNestedReferenceNestedFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreNestedReferenceNestedFieldRule = PreNestedReferenceNestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreGuidanceFieldFormat),+    path :: !(Maybe PathReferenceRule),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreNestedReferenceFrontmatterRules = PreNestedReferenceFrontmatterRules+  { required :: ![PreNestedReferenceFieldRule],+    recommended :: ![PreNestedReferenceFieldRule],+    optional :: ![PreNestedReferenceFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreNestedReferenceProfileSpec = PreNestedReferenceProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !PreNestedReferenceFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    requireBundleVersion :: !(Maybe Text),+    types :: ![PreNestedReferenceTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreNestedReferenceTypeRule = PreNestedReferenceTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !PreNestedReferenceFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall PreNestedReferenceTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The complete descriptor generation frozen before a profile could require its+-- bundle to declare an OKF version. This is the immediately preceding public+-- descriptor generation: it is today's shape minus the @requireBundleVersion@+-- member on the top-level record. That member is the only difference, so every+-- rule record, every type rule, and every union is unchanged and is shared+-- rather than copied — the freezing rule of+-- @docs\/adr\/11-growing-the-profile-descriptor-language.md@ is about the+-- descriptor as a whole, and a generation that changes one record copies only+-- what changed. Exercised by+-- @okf-core\/test\/fixtures\/profiles\/pre-bundle-version.dhall@.+data PreBundleVersionProfileSpec = PreBundleVersionProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !PreNestedReferenceFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    types :: ![PreNestedReferenceTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | The complete descriptor generation frozen before path-valued reference+-- rules were added: today's shape minus the @path@ member on 'FieldRule' and on+-- 'NestedFieldRule'. Because that is a record addition rather than a union+-- widening, 'Cardinality', 'FieldFormat', 'FieldCondition', and+-- 'HandleReferenceRule' are unchanged by it and so are shared rather than+-- copied; the two rule records and everything that contains them are copied.+-- Exercised by @okf-core\/test\/fixtures\/profiles\/path-references-mp8-ep3.dhall@.+data PrePathProfileFieldRule = PrePathProfileFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreGuidanceFieldFormat),+    elementFields :: !(Maybe PrePathProfileNestedRules),+    objectFields :: !(Maybe PrePathProfileNestedRules),+    reference :: !(Maybe PreNestedReferenceHandleReferenceRule),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PrePathProfileNestedRules = PrePathProfileNestedRules+  { required :: ![PrePathProfileNestedFieldRule],+    recommended :: ![PrePathProfileNestedFieldRule],+    optional :: ![PrePathProfileNestedFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PrePathProfileNestedFieldRule = PrePathProfileNestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreGuidanceFieldFormat),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PrePathProfileFrontmatterRules = PrePathProfileFrontmatterRules+  { required :: ![PrePathProfileFieldRule],+    recommended :: ![PrePathProfileFieldRule],+    optional :: ![PrePathProfileFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PrePathProfileSpec = PrePathProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !PrePathProfileFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    types :: ![PrePathProfileTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PrePathProfileTypeRule = PrePathProfileTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !PrePathProfileFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall PrePathProfileTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The complete object-rule descriptor generation, frozen before the OKF v0.2+-- value formats were added to 'FieldFormat'. Its records match the shape+-- 'PrePathProfileFieldRule' froze — no @path@ member — and the further+-- difference is that every @format@ member refers to the frozen+-- five-alternative 'PreV02FieldFormat'. Exercised by+-- @okf-core\/test\/fixtures\/profiles\/formats-mp8-ep2.dhall@.+data PreActorProfileFieldRule = PreActorProfileFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat),+    elementFields :: !(Maybe PreActorProfileNestedRules),+    objectFields :: !(Maybe PreActorProfileNestedRules),+    reference :: !(Maybe PreNestedReferenceHandleReferenceRule),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreActorProfileNestedRules = PreActorProfileNestedRules+  { required :: ![PreActorProfileNestedFieldRule],+    recommended :: ![PreActorProfileNestedFieldRule],+    optional :: ![PreActorProfileNestedFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreActorProfileNestedFieldRule = PreActorProfileNestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreActorProfileFrontmatterRules = PreActorProfileFrontmatterRules+  { required :: ![PreActorProfileFieldRule],+    recommended :: ![PreActorProfileFieldRule],+    optional :: ![PreActorProfileFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreActorProfileSpec = PreActorProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !PreActorProfileFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    types :: ![PreActorProfileTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreActorProfileTypeRule = PreActorProfileTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !PreActorProfileFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall PreActorProfileTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The complete optional-presence descriptor generation, frozen before object+-- rules were added: it matches the shape before @objectFields@ was added to+-- 'FieldRule'. 'Cardinality', 'HandleReferenceRule', and 'FieldCondition' are+-- unchanged by every addition since and so are shared rather than copied; the+-- nested rule types are copied because their @format@ member now refers to the+-- frozen 'PreV02FieldFormat'. Exercised by+-- @okf-core\/test\/fixtures\/profiles\/object-fields-mp8-ep1.dhall@.+data PreObjectProfileFieldRule = PreObjectProfileFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat),+    elementFields :: !(Maybe PreObjectProfileNestedRules),+    reference :: !(Maybe PreNestedReferenceHandleReferenceRule),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreObjectProfileNestedRules = PreObjectProfileNestedRules+  { required :: ![PreObjectProfileNestedFieldRule],+    recommended :: ![PreObjectProfileNestedFieldRule],+    optional :: ![PreObjectProfileNestedFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreObjectProfileNestedFieldRule = PreObjectProfileNestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreObjectProfileFrontmatterRules = PreObjectProfileFrontmatterRules+  { required :: ![PreObjectProfileFieldRule],+    recommended :: ![PreObjectProfileFieldRule],+    optional :: ![PreObjectProfileFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreObjectProfileSpec = PreObjectProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !PreObjectProfileFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    types :: ![PreObjectProfileTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreObjectProfileTypeRule = PreObjectProfileTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !PreObjectProfileFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall PreObjectProfileTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The complete reference-aware descriptor generation, frozen before the+-- @optional@ presence list was added to 'FrontmatterRules' and 'NestedRules'.+-- This is the immediately preceding public descriptor generation: it matches+-- today's shape exactly apart from that third list, so every descriptor written+-- as a record literal against the published schema keeps loading. Exercised by+-- @okf-core\/test\/fixtures\/profiles\/document-references-ep3.dhall@.+data ReferenceProfileFieldRule = ReferenceProfileFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat),+    elementFields :: !(Maybe ReferenceProfileNestedRules),+    reference :: !(Maybe PreNestedReferenceHandleReferenceRule),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data ReferenceProfileNestedRules = ReferenceProfileNestedRules+  { required :: ![ReferenceProfileNestedFieldRule],+    recommended :: ![ReferenceProfileNestedFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data ReferenceProfileNestedFieldRule = ReferenceProfileNestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data ReferenceProfileFrontmatterRules = ReferenceProfileFrontmatterRules+  { required :: ![ReferenceProfileFieldRule],+    recommended :: ![ReferenceProfileFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data ReferenceProfileSpec = ReferenceProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !ReferenceProfileFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    types :: ![ReferenceProfileTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data ReferenceProfileTypeRule = ReferenceProfileTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !ReferenceProfileFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall ReferenceProfileTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The complete condition-aware descriptor generation, frozen before+-- top-level document-reference policies were added.+data ConditionalProfileFieldRule = ConditionalProfileFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat),+    elementFields :: !(Maybe ConditionalProfileNestedRules),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data ConditionalProfileNestedRules = ConditionalProfileNestedRules+  { required :: ![ConditionalProfileNestedFieldRule],+    recommended :: ![ConditionalProfileNestedFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data ConditionalProfileNestedFieldRule = ConditionalProfileNestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat),+    when :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data ConditionalProfileFrontmatterRules = ConditionalProfileFrontmatterRules+  { required :: ![ConditionalProfileFieldRule],+    recommended :: ![ConditionalProfileFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data ConditionalProfileSpec = ConditionalProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !ConditionalProfileFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    types :: ![ConditionalProfileTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data ConditionalProfileTypeRule = ConditionalProfileTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !ConditionalProfileFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall ConditionalProfileTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The complete bounded-nested descriptor generation, frozen before+-- same-scope field conditions were added. This is the immediately preceding+-- public descriptor generation.+data NestedProfileFieldRule = NestedProfileFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat),+    elementFields :: !(Maybe NestedProfileRules)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data NestedProfileRules = NestedProfileRules+  { required :: ![NestedProfileNestedFieldRule],+    recommended :: ![NestedProfileNestedFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data NestedProfileNestedFieldRule = NestedProfileNestedFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data NestedProfileFrontmatterRules = NestedProfileFrontmatterRules+  { required :: ![NestedProfileFieldRule],+    recommended :: ![NestedProfileFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data NestedProfileSpec = NestedProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !NestedProfileFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    types :: ![NestedProfileTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data NestedProfileTypeRule = NestedProfileTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !NestedProfileFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall NestedProfileTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The complete EP-4 field rule, frozen before one-level nested records were+-- added. This is the immediately preceding public descriptor generation.+data FormatFieldRule = FormatFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe PreV02FieldFormat)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data FormatFrontmatterRules = FormatFrontmatterRules+  { required :: ![FormatFieldRule],+    recommended :: ![FormatFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data FormatProfileSpec = FormatProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !FormatFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    types :: ![FormatTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data FormatTypeRule = FormatTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !FormatFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall FormatTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The EP-3 field rule, frozen before named formats were added.+data CardinalityFieldRule = CardinalityFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data CardinalityFrontmatterRules = CardinalityFrontmatterRules+  { required :: ![CardinalityFieldRule],+    recommended :: ![CardinalityFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | The complete EP-3 profile shape, frozen before named formats were added.+data CardinalityProfileSpec = CardinalityProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !CardinalityFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    types :: ![CardinalityTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data CardinalityTypeRule = CardinalityTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !CardinalityFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall CardinalityTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The EP-2 field rule, frozen before cardinality was added.+data VocabularyFieldRule = VocabularyFieldRule+  { field :: !Text,+    description :: !(Maybe Text),+    allowedValues :: ![Text]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data VocabularyFrontmatterRules = VocabularyFrontmatterRules+  { required :: ![VocabularyFieldRule],+    recommended :: ![VocabularyFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | The EP-2 profile shape, frozen before cardinality was added.+data VocabularyProfileSpec = VocabularyProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !VocabularyFrontmatterRules,+    allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    types :: ![VocabularyTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data VocabularyTypeRule = VocabularyTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !VocabularyFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall VocabularyTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | A field rule from either self-documenting schema generation, before value+-- vocabularies were added.+data PreviousFieldRule = PreviousFieldRule+  { field :: !Text,+    description :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data PreviousFrontmatterRules = PreviousFrontmatterRules+  { required :: ![PreviousFieldRule],+    recommended :: ![PreviousFieldRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++-- | The type-aware shape from EP-1, frozen before vocabularies and field-name+-- closure were added.+data TypeAwareProfileSpec = TypeAwareProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !PreviousFrontmatterRules,+    allowUnknownTypes :: !Bool,+    idField :: !(Maybe Text),+    types :: ![TypeAwareTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data TypeAwareTypeRule = TypeAwareTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    frontmatter :: !PreviousFrontmatterRules,+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall TypeAwareTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++-- | The self-documenting profile shape published immediately before+-- type-specific frontmatter rules. It is frozen as a compatibility decoder in+-- exactly the same way as the older 0.2.x shape below.+data DescribedProfileSpec = DescribedProfileSpec+  { name :: !Text,+    description :: !(Maybe Text),+    okfVersion :: !Text,+    frontmatter :: !PreviousFrontmatterRules,+    allowUnknownTypes :: !Bool,+    idField :: !(Maybe Text),+    types :: ![DescribedTypeRule]+  }+  deriving stock (Generic, Eq, Show)+  deriving anyclass (FromDhall)++data DescribedTypeRule = DescribedTypeRule+  { type_ :: !Text,+    description :: !(Maybe Text),+    pathPattern :: !(Maybe Text),+    resourceScheme :: !(Maybe Text),+    requireSchemaSection :: !Bool,+    schemaColumns :: ![Text],+    idPrefix :: !(Maybe Text)+  }+  deriving stock (Generic, Eq, Show)++instance FromDhall DescribedTypeRule where+  autoWith _normalizer =+    genericAutoWith+      (Dhall.defaultInterpretOptions {Dhall.fieldModifier = stripTrailingUnderscore})+    where+      stripTrailingUnderscore fieldName =+        fromMaybe fieldName (Text.stripSuffix "_" fieldName)++emptyFrontmatterRules :: FrontmatterRules+emptyFrontmatterRules = FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [], recommended = [], optional = []}++upgradePreGuidanceCardinality :: PreGuidanceCardinality -> Cardinality+upgradePreGuidanceCardinality = \case+  PreGuidanceAny -> Any+  PreGuidanceScalar -> Scalar+  PreGuidanceList -> List++upgradePreGuidanceFieldFormat :: PreGuidanceFieldFormat -> FieldFormat+upgradePreGuidanceFieldFormat = \case+  PreGuidanceRfc3339Utc -> Rfc3339Utc+  PreGuidanceDate -> Date+  PreGuidanceUri -> Uri+  PreGuidanceUriWithScheme scheme -> UriWithScheme scheme+  PreGuidanceDocumentHandle prefix -> DocumentHandle prefix+  PreGuidanceActor -> Actor+  PreGuidanceHumanActor -> HumanActor+  PreGuidanceInteger -> Integer+  PreGuidanceNonNegativeInteger -> NonNegativeInteger+  PreGuidanceBoolean -> Boolean++upgradePreGuidanceCondition :: PreGuidanceFieldCondition -> FieldCondition+upgradePreGuidanceCondition previous =+  FieldCondition+    { field = previous ^. #field,+      hasValue = previous ^. #hasValue+    }++upgradePreGuidanceHandleRule :: PreGuidanceHandleReferenceRule -> HandleReferenceRule+upgradePreGuidanceHandleRule previous =+  HandleReferenceRule+    { localPrefix = previous ^. #localPrefix,+      externalUriSchemes = previous ^. #externalUriSchemes,+      allowSelf = previous ^. #allowSelf,+      allowLocal = previous ^. #allowLocal,+      externalUriPattern = previous ^. #externalUriPattern+    }++upgradePreGuidancePathRule :: PreGuidancePathReferenceRule -> PathReferenceRule+upgradePreGuidancePathRule previous =+  PathReferenceRule+    { externalUriSchemes = previous ^. #externalUriSchemes,+      allowSelf = previous ^. #allowSelf+    }++upgradePreNestedClosureProfileSpec :: PreNestedClosureProfileSpec -> ProfileSpec+upgradePreNestedClosureProfileSpec previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = previous ^. #guidance,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradePreNestedClosureFrontmatterRules (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = previous ^. #requireBundleVersion,+      types = map upgradePreNestedClosureTypeRule (previous ^. #types)+    }++upgradePreNestedClosureTypeRule :: PreNestedClosureTypeRule -> TypeRule+upgradePreNestedClosureTypeRule previous =+  TypeRule+    { type_ = previous ^. #type_,+      description = previous ^. #description,+      guidance = previous ^. #guidance,+      frontmatter = upgradePreNestedClosureFrontmatterRules (previous ^. #frontmatter),+      pathPattern = previous ^. #pathPattern,+      resourceScheme = previous ^. #resourceScheme,+      requireSchemaSection = previous ^. #requireSchemaSection,+      schemaColumns = previous ^. #schemaColumns,+      idPrefix = previous ^. #idPrefix+    }++upgradePreNestedClosureFrontmatterRules :: PreNestedClosureFrontmatterRules -> FrontmatterRules+upgradePreNestedClosureFrontmatterRules previous =+  FrontmatterRules+    { required = map upgradePreNestedClosureFieldRule (previous ^. #required),+      recommended = map upgradePreNestedClosureFieldRule (previous ^. #recommended),+      optional = map upgradePreNestedClosureFieldRule (previous ^. #optional),+      presenceConstraints = map upgradePreNestedClosurePresenceConstraint (previous ^. #presenceConstraints),+      timestampOrderConstraints = map upgradePreNestedClosureTimestampOrderConstraint (previous ^. #timestampOrderConstraints),+      membershipConstraints = map upgradePreNestedClosureMembershipConstraint (previous ^. #membershipConstraints),+      uniqueValuesConstraints = map upgradePreNestedClosureUniqueValuesConstraint (previous ^. #uniqueValuesConstraints)+    }++upgradePreNestedClosureFieldRule :: PreNestedClosureFieldRule -> FieldRule+upgradePreNestedClosureFieldRule previous =+  FieldRule+    { field = previous ^. #field,+      description = previous ^. #description,+      allowedValues = previous ^. #allowedValues,+      cardinality = upgradePreNestedClosureCardinality (previous ^. #cardinality),+      format = upgradePreNestedClosureFieldFormat <$> previous ^. #format,+      elementFields = upgradePreNestedClosureNestedRules <$> previous ^. #elementFields,+      objectFields = upgradePreNestedClosureNestedRules <$> previous ^. #objectFields,+      reference = upgradePreNestedClosureHandleReferenceRule <$> previous ^. #reference,+      path = upgradePreNestedClosurePathReferenceRule <$> previous ^. #path,+      when = upgradePreNestedClosureFieldCondition <$> previous ^. #when,+      uniqueBy = previous ^. #uniqueBy+    }++upgradePreNestedClosureNestedRules :: PreNestedClosureNestedRules -> NestedRules+upgradePreNestedClosureNestedRules previous =+  NestedRules+    { allowUnknownFields = True,+      required = map upgradePreNestedClosureNestedFieldRule (previous ^. #required),+      recommended = map upgradePreNestedClosureNestedFieldRule (previous ^. #recommended),+      optional = map upgradePreNestedClosureNestedFieldRule (previous ^. #optional),+      presenceConstraints = map upgradePreNestedClosurePresenceConstraint (previous ^. #presenceConstraints),+      timestampOrderConstraints = map upgradePreNestedClosureTimestampOrderConstraint (previous ^. #timestampOrderConstraints)+    }++upgradePreNestedClosureNestedFieldRule :: PreNestedClosureNestedFieldRule -> NestedFieldRule+upgradePreNestedClosureNestedFieldRule previous =+  NestedFieldRule+    { field = previous ^. #field,+      description = previous ^. #description,+      allowedValues = previous ^. #allowedValues,+      cardinality = upgradePreNestedClosureCardinality (previous ^. #cardinality),+      format = upgradePreNestedClosureFieldFormat <$> previous ^. #format,+      path = upgradePreNestedClosurePathReferenceRule <$> previous ^. #path,+      when = upgradePreNestedClosureFieldCondition <$> previous ^. #when,+      reference = upgradePreNestedClosureHandleReferenceRule <$> previous ^. #reference+    }++upgradePreNestedClosureFieldCondition :: PreNestedClosureFieldCondition -> FieldCondition+upgradePreNestedClosureFieldCondition previous =+  FieldCondition+    { field = previous ^. #field,+      hasValue = previous ^. #hasValue+    }++upgradePreNestedClosureHandleReferenceRule :: PreNestedClosureHandleReferenceRule -> HandleReferenceRule+upgradePreNestedClosureHandleReferenceRule previous =+  HandleReferenceRule+    { localPrefix = previous ^. #localPrefix,+      externalUriSchemes = previous ^. #externalUriSchemes,+      allowSelf = previous ^. #allowSelf,+      allowLocal = previous ^. #allowLocal,+      externalUriPattern = previous ^. #externalUriPattern+    }++upgradePreNestedClosurePathReferenceRule :: PreNestedClosurePathReferenceRule -> PathReferenceRule+upgradePreNestedClosurePathReferenceRule previous =+  PathReferenceRule+    { externalUriSchemes = previous ^. #externalUriSchemes,+      allowSelf = previous ^. #allowSelf+    }++upgradePreNestedClosureValueSelector :: PreNestedClosureValueSelector -> ValueSelector+upgradePreNestedClosureValueSelector previous =+  ValueSelector+    { field = previous ^. #field,+      member = previous ^. #member+    }++upgradePreNestedClosurePresenceConstraint :: PreNestedClosurePresenceConstraint -> PresenceConstraint+upgradePreNestedClosurePresenceConstraint previous =+  PresenceConstraint+    { when = upgradePreNestedClosureFieldCondition <$> previous ^. #when,+      whenAnyPresent = map upgradePreNestedClosureValueSelector (previous ^. #whenAnyPresent),+      requireAll = map upgradePreNestedClosureValueSelector (previous ^. #requireAll),+      requireAny = map upgradePreNestedClosureValueSelector (previous ^. #requireAny)+    }++upgradePreNestedClosureTimestampOrderConstraint :: PreNestedClosureTimestampOrderConstraint -> TimestampOrderConstraint+upgradePreNestedClosureTimestampOrderConstraint previous =+  TimestampOrderConstraint+    { before = previous ^. #before,+      after = previous ^. #after+    }++upgradePreNestedClosureMembershipConstraint :: PreNestedClosureMembershipConstraint -> MembershipConstraint+upgradePreNestedClosureMembershipConstraint previous =+  MembershipConstraint+    { source = upgradePreNestedClosureValueSelector (previous ^. #source),+      target = upgradePreNestedClosureValueSelector (previous ^. #target)+    }++upgradePreNestedClosureUniqueValuesConstraint :: PreNestedClosureUniqueValuesConstraint -> UniqueValuesConstraint+upgradePreNestedClosureUniqueValuesConstraint previous =+  UniqueValuesConstraint+    { selectors = map upgradePreNestedClosureValueSelector (previous ^. #selectors)+    }++upgradePreNestedClosureCardinality :: PreNestedClosureCardinality -> Cardinality+upgradePreNestedClosureCardinality = \case+  PreNestedClosureAny -> Any+  PreNestedClosureScalar -> Scalar+  PreNestedClosureList -> List++upgradePreNestedClosureFieldFormat :: PreNestedClosureFieldFormat -> FieldFormat+upgradePreNestedClosureFieldFormat = \case+  PreNestedClosureRfc3339Utc -> Rfc3339Utc+  PreNestedClosureDate -> Date+  PreNestedClosureUri -> Uri+  PreNestedClosureUriWithScheme value -> UriWithScheme value+  PreNestedClosureDocumentHandle value -> DocumentHandle value+  PreNestedClosureActor -> Actor+  PreNestedClosureHumanActor -> HumanActor+  PreNestedClosureInteger -> Integer+  PreNestedClosureNonNegativeInteger -> NonNegativeInteger+  PreNestedClosureBoolean -> Boolean+  PreNestedClosureFiniteDecimal -> FiniteDecimal++upgradePreProductDiscoveryFrontmatter :: PreProductDiscoveryFrontmatterRules -> FrontmatterRules+upgradePreProductDiscoveryFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = map upgradeField (previous ^. #optional)+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = upgradePreGuidanceCardinality (rule ^. #cardinality),+          format = upgradePreGuidanceFieldFormat <$> rule ^. #format,+          elementFields = upgradeNestedRules <$> rule ^. #elementFields,+          objectFields = upgradeNestedRules <$> rule ^. #objectFields,+          reference = upgradePreGuidanceHandleRule <$> rule ^. #reference,+          path = upgradePreGuidancePathRule <$> rule ^. #path,+          when = upgradePreGuidanceCondition <$> rule ^. #when,+          uniqueBy = rule ^. #uniqueBy+        }+    upgradeNestedRules rules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required = map upgradeNestedField (rules ^. #required),+          recommended = map upgradeNestedField (rules ^. #recommended),+          optional = map upgradeNestedField (rules ^. #optional)+        }+    upgradeNestedField rule =+      NestedFieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = upgradePreGuidanceCardinality (rule ^. #cardinality),+          format = upgradePreGuidanceFieldFormat <$> rule ^. #format,+          path = upgradePreGuidancePathRule <$> rule ^. #path,+          when = upgradePreGuidanceCondition <$> rule ^. #when,+          reference = upgradePreGuidanceHandleRule <$> rule ^. #reference+        }++upgradePreProductDiscoveryTypeRule :: PreProductDiscoveryTypeRule -> TypeRule+upgradePreProductDiscoveryTypeRule rule =+  TypeRule+    { type_ = rule ^. #type_,+      description = rule ^. #description,+      guidance = rule ^. #guidance,+      frontmatter = upgradePreProductDiscoveryFrontmatter (rule ^. #frontmatter),+      pathPattern = rule ^. #pathPattern,+      resourceScheme = rule ^. #resourceScheme,+      requireSchemaSection = rule ^. #requireSchemaSection,+      schemaColumns = rule ^. #schemaColumns,+      idPrefix = rule ^. #idPrefix+    }++upgradePreProductDiscoveryProfile :: PreProductDiscoveryProfileSpec -> ProfileSpec+upgradePreProductDiscoveryProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = previous ^. #guidance,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradePreProductDiscoveryFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = previous ^. #requireBundleVersion,+      types = map upgradePreProductDiscoveryTypeRule (previous ^. #types)+    }++upgradePreGuidanceFrontmatter :: PreGuidanceFrontmatterRules -> FrontmatterRules+upgradePreGuidanceFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = map upgradeField (previous ^. #optional)+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = upgradePreGuidanceCardinality (rule ^. #cardinality),+          format = upgradePreGuidanceFieldFormat <$> rule ^. #format,+          elementFields = upgradeNestedRules <$> rule ^. #elementFields,+          objectFields = upgradeNestedRules <$> rule ^. #objectFields,+          reference = upgradePreGuidanceHandleRule <$> rule ^. #reference,+          path = upgradePreGuidancePathRule <$> rule ^. #path,+          when = upgradePreGuidanceCondition <$> rule ^. #when,+          uniqueBy = rule ^. #uniqueBy+        }+    upgradeNestedRules rules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required = map upgradeNestedField (rules ^. #required),+          recommended = map upgradeNestedField (rules ^. #recommended),+          optional = map upgradeNestedField (rules ^. #optional)+        }+    upgradeNestedField rule =+      NestedFieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = upgradePreGuidanceCardinality (rule ^. #cardinality),+          format = upgradePreGuidanceFieldFormat <$> rule ^. #format,+          path = upgradePreGuidancePathRule <$> rule ^. #path,+          when = upgradePreGuidanceCondition <$> rule ^. #when,+          reference = upgradePreGuidanceHandleRule <$> rule ^. #reference+        }++upgradePreGuidanceTypeRule :: PreGuidanceTypeRule -> TypeRule+upgradePreGuidanceTypeRule rule =+  TypeRule+    { type_ = rule ^. #type_,+      description = rule ^. #description,+      guidance = Nothing,+      frontmatter = upgradePreGuidanceFrontmatter (rule ^. #frontmatter),+      pathPattern = rule ^. #pathPattern,+      resourceScheme = rule ^. #resourceScheme,+      requireSchemaSection = rule ^. #requireSchemaSection,+      schemaColumns = rule ^. #schemaColumns,+      idPrefix = rule ^. #idPrefix+    }++upgradePreGuidanceProfile :: PreGuidanceProfileSpec -> ProfileSpec+upgradePreGuidanceProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradePreGuidanceFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = previous ^. #requireBundleVersion,+      types = map upgradePreGuidanceTypeRule (previous ^. #types)+    }++upgradePreNestedReferenceHandleRule :: PreNestedReferenceHandleReferenceRule -> HandleReferenceRule+upgradePreNestedReferenceHandleRule previous =+  HandleReferenceRule+    { localPrefix = previous ^. #localPrefix,+      externalUriSchemes = previous ^. #externalUriSchemes,+      allowSelf = previous ^. #allowSelf,+      allowLocal = True,+      externalUriPattern = Nothing+    }++upgradePreNestedReferenceFrontmatter :: PreNestedReferenceFrontmatterRules -> FrontmatterRules+upgradePreNestedReferenceFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = map upgradeField (previous ^. #optional)+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreGuidanceFieldFormat <$> rule ^. #format,+          elementFields = upgradeNestedRules <$> rule ^. #elementFields,+          objectFields = upgradeNestedRules <$> rule ^. #objectFields,+          reference = upgradePreNestedReferenceHandleRule <$> rule ^. #reference,+          path = rule ^. #path,+          when = rule ^. #when,+          uniqueBy = Nothing+        }+    upgradeNestedRules rules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required = map upgradeNestedField (rules ^. #required),+          recommended = map upgradeNestedField (rules ^. #recommended),+          optional = map upgradeNestedField (rules ^. #optional)+        }+    upgradeNestedField rule =+      NestedFieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreGuidanceFieldFormat <$> rule ^. #format,+          path = rule ^. #path,+          when = rule ^. #when,+          reference = Nothing+        }++upgradePreNestedReferenceTypeRule :: PreNestedReferenceTypeRule -> TypeRule+upgradePreNestedReferenceTypeRule rule =+  TypeRule+    { type_ = rule ^. #type_,+      description = rule ^. #description,+      guidance = Nothing,+      frontmatter = upgradePreNestedReferenceFrontmatter (rule ^. #frontmatter),+      pathPattern = rule ^. #pathPattern,+      resourceScheme = rule ^. #resourceScheme,+      requireSchemaSection = rule ^. #requireSchemaSection,+      schemaColumns = rule ^. #schemaColumns,+      idPrefix = rule ^. #idPrefix+    }++upgradePreNestedReferenceProfile :: PreNestedReferenceProfileSpec -> ProfileSpec+upgradePreNestedReferenceProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradePreNestedReferenceFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = previous ^. #requireBundleVersion,+      types = map upgradePreNestedReferenceTypeRule (previous ^. #types)+    }++upgradePrePathProfileFrontmatter :: PrePathProfileFrontmatterRules -> FrontmatterRules+upgradePrePathProfileFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = map upgradeField (previous ^. #optional)+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreGuidanceFieldFormat <$> rule ^. #format,+          elementFields = upgradeNestedRules <$> rule ^. #elementFields,+          objectFields = upgradeNestedRules <$> rule ^. #objectFields,+          reference = upgradePreNestedReferenceHandleRule <$> rule ^. #reference,+          path = Nothing,+          when = rule ^. #when,+          uniqueBy = Nothing+        }+    upgradeNestedRules rules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required = map upgradeNestedField (rules ^. #required),+          recommended = map upgradeNestedField (rules ^. #recommended),+          optional = map upgradeNestedField (rules ^. #optional)+        }+    upgradeNestedField rule =+      NestedFieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreGuidanceFieldFormat <$> rule ^. #format,+          path = Nothing,+          when = rule ^. #when,+          reference = Nothing+        }++upgradePreActorProfileFrontmatter :: PreActorProfileFrontmatterRules -> FrontmatterRules+upgradePreActorProfileFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = map upgradeField (previous ^. #optional)+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          elementFields = upgradeNestedRules <$> rule ^. #elementFields,+          objectFields = upgradeNestedRules <$> rule ^. #objectFields,+          reference = upgradePreNestedReferenceHandleRule <$> rule ^. #reference,+          path = Nothing,+          when = rule ^. #when,+          uniqueBy = Nothing+        }+    upgradeNestedRules rules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required = map upgradeNestedField (rules ^. #required),+          recommended = map upgradeNestedField (rules ^. #recommended),+          optional = map upgradeNestedField (rules ^. #optional)+        }+    upgradeNestedField rule =+      NestedFieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          path = Nothing,+          when = rule ^. #when,+          reference = Nothing+        }++upgradePreObjectProfileFrontmatter :: PreObjectProfileFrontmatterRules -> FrontmatterRules+upgradePreObjectProfileFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = map upgradeField (previous ^. #optional)+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          elementFields = upgradeNestedRules <$> rule ^. #elementFields,+          objectFields = Nothing,+          reference = upgradePreNestedReferenceHandleRule <$> rule ^. #reference,+          path = Nothing,+          when = rule ^. #when,+          uniqueBy = Nothing+        }+    upgradeNestedRules rules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required = map upgradeNestedField (rules ^. #required),+          recommended = map upgradeNestedField (rules ^. #recommended),+          optional = map upgradeNestedField (rules ^. #optional)+        }+    upgradeNestedField rule =+      NestedFieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          path = Nothing,+          when = rule ^. #when,+          reference = Nothing+        }++upgradeReferenceProfileFrontmatter :: ReferenceProfileFrontmatterRules -> FrontmatterRules+upgradeReferenceProfileFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = []+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          elementFields = upgradeNestedRules <$> rule ^. #elementFields,+          objectFields = Nothing,+          reference = upgradePreNestedReferenceHandleRule <$> rule ^. #reference,+          path = Nothing,+          when = rule ^. #when,+          uniqueBy = Nothing+        }+    upgradeNestedRules rules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required = map upgradeNestedField (rules ^. #required),+          recommended = map upgradeNestedField (rules ^. #recommended),+          optional = []+        }+    upgradeNestedField rule =+      NestedFieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          path = Nothing,+          when = rule ^. #when,+          reference = Nothing+        }++upgradePreviousFrontmatter :: PreviousFrontmatterRules -> FrontmatterRules+upgradePreviousFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = []+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = [],+          cardinality = Any,+          format = Nothing,+          elementFields = Nothing,+          objectFields = Nothing,+          reference = Nothing,+          path = Nothing,+          when = Nothing,+          uniqueBy = Nothing+        }++upgradeConditionalProfileFrontmatter :: ConditionalProfileFrontmatterRules -> FrontmatterRules+upgradeConditionalProfileFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = []+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          elementFields = upgradeNestedRules <$> rule ^. #elementFields,+          objectFields = Nothing,+          reference = Nothing,+          path = Nothing,+          when = rule ^. #when,+          uniqueBy = Nothing+        }+    upgradeNestedRules rules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required = map upgradeNestedField (rules ^. #required),+          recommended = map upgradeNestedField (rules ^. #recommended),+          optional = []+        }+    upgradeNestedField rule =+      NestedFieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          path = Nothing,+          when = rule ^. #when,+          reference = Nothing+        }++upgradeNestedProfileFrontmatter :: NestedProfileFrontmatterRules -> FrontmatterRules+upgradeNestedProfileFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = []+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          elementFields = upgradeNestedProfileRules <$> rule ^. #elementFields,+          objectFields = Nothing,+          reference = Nothing,+          path = Nothing,+          when = Nothing,+          uniqueBy = Nothing+        }+    upgradeNestedProfileRules rules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required = map upgradeNestedField (rules ^. #required),+          recommended = map upgradeNestedField (rules ^. #recommended),+          optional = []+        }+    upgradeNestedField rule =+      NestedFieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          path = Nothing,+          when = Nothing,+          reference = Nothing+        }++upgradeFormatFrontmatter :: FormatFrontmatterRules -> FrontmatterRules+upgradeFormatFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = []+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = upgradePreV02FieldFormat <$> rule ^. #format,+          elementFields = Nothing,+          objectFields = Nothing,+          reference = Nothing,+          path = Nothing,+          when = Nothing,+          uniqueBy = Nothing+        }++upgradeCardinalityFrontmatter :: CardinalityFrontmatterRules -> FrontmatterRules+upgradeCardinalityFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = []+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = Nothing,+          elementFields = Nothing,+          objectFields = Nothing,+          reference = Nothing,+          path = Nothing,+          when = Nothing,+          uniqueBy = Nothing+        }++upgradeVocabularyFrontmatter :: VocabularyFrontmatterRules -> FrontmatterRules+upgradeVocabularyFrontmatter previous =+  FrontmatterRules+    { membershipConstraints = [],+      uniqueValuesConstraints = [],+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = map upgradeField (previous ^. #required),+      recommended = map upgradeField (previous ^. #recommended),+      optional = []+    }+  where+    upgradeField rule =+      FieldRule+        { field = rule ^. #field,+          description = rule ^. #description,+          allowedValues = rule ^. #allowedValues,+          cardinality = Any,+          format = Nothing,+          elementFields = Nothing,+          objectFields = Nothing,+          reference = Nothing,+          path = Nothing,+          when = Nothing,+          uniqueBy = Nothing+        }++-- | Lift the generation frozen before @requireBundleVersion@ forward. Its+-- contained rule records use the shared 0.7.0.0 frozen types because those+-- records later grew too.+upgradePreBundleVersionProfile :: PreBundleVersionProfileSpec -> ProfileSpec+upgradePreBundleVersionProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradePreNestedReferenceFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradePreNestedReferenceTypeRule (previous ^. #types)+    }++upgradePrePathProfile :: PrePathProfileSpec -> ProfileSpec+upgradePrePathProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradePrePathProfileFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (previous ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = upgradePrePathProfileFrontmatter (rule ^. #frontmatter),+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++upgradePreActorProfile :: PreActorProfileSpec -> ProfileSpec+upgradePreActorProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradePreActorProfileFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (previous ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = upgradePreActorProfileFrontmatter (rule ^. #frontmatter),+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++upgradePreObjectProfile :: PreObjectProfileSpec -> ProfileSpec+upgradePreObjectProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradePreObjectProfileFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (previous ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = upgradePreObjectProfileFrontmatter (rule ^. #frontmatter),+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++upgradeReferenceProfile :: ReferenceProfileSpec -> ProfileSpec+upgradeReferenceProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradeReferenceProfileFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (previous ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = upgradeReferenceProfileFrontmatter (rule ^. #frontmatter),+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++upgradeConditionalProfile :: ConditionalProfileSpec -> ProfileSpec+upgradeConditionalProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradeConditionalProfileFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (previous ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = upgradeConditionalProfileFrontmatter (rule ^. #frontmatter),+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++upgradeNestedProfile :: NestedProfileSpec -> ProfileSpec+upgradeNestedProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradeNestedProfileFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (previous ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = upgradeNestedProfileFrontmatter (rule ^. #frontmatter),+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++upgradeFormatProfile :: FormatProfileSpec -> ProfileSpec+upgradeFormatProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradeFormatFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (previous ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = upgradeFormatFrontmatter (rule ^. #frontmatter),+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++upgradeCardinalityProfile :: CardinalityProfileSpec -> ProfileSpec+upgradeCardinalityProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradeCardinalityFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (previous ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = upgradeCardinalityFrontmatter (rule ^. #frontmatter),+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++upgradeVocabularyProfile :: VocabularyProfileSpec -> ProfileSpec+upgradeVocabularyProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradeVocabularyFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = previous ^. #allowUnknownFields,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (previous ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = upgradeVocabularyFrontmatter (rule ^. #frontmatter),+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++upgradeTypeAwareProfile :: TypeAwareProfileSpec -> ProfileSpec+upgradeTypeAwareProfile previous =+  ProfileSpec+    { name = previous ^. #name,+      description = previous ^. #description,+      guidance = Nothing,+      okfVersion = previous ^. #okfVersion,+      frontmatter = upgradePreviousFrontmatter (previous ^. #frontmatter),+      allowUnknownTypes = previous ^. #allowUnknownTypes,+      allowUnknownFields = True,+      idField = previous ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (previous ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = upgradePreviousFrontmatter (rule ^. #frontmatter),+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++upgradeDescribedProfile :: DescribedProfileSpec -> ProfileSpec+upgradeDescribedProfile described =+  ProfileSpec+    { name = described ^. #name,+      description = described ^. #description,+      guidance = Nothing,+      okfVersion = described ^. #okfVersion,+      frontmatter = upgradePreviousFrontmatter (described ^. #frontmatter),+      allowUnknownTypes = described ^. #allowUnknownTypes,+      allowUnknownFields = True,+      idField = described ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (described ^. #types)+    }+  where+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = rule ^. #description,+          guidance = Nothing,+          frontmatter = emptyFrontmatterRules,+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++-- | Lift a 0.2.x profile into the current shape by attaching neither+-- descriptions nor guidance, and by supplying empty type-specific frontmatter.+upgradeLegacyProfile :: LegacyProfileSpec -> ProfileSpec+upgradeLegacyProfile legacy =+  ProfileSpec+    { name = legacy ^. #name,+      description = Nothing,+      guidance = Nothing,+      okfVersion = legacy ^. #okfVersion,+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = map undocumented (legacy ^. #frontmatter . #required),+            recommended = map undocumented (legacy ^. #frontmatter . #recommended),+            optional = []+          },+      allowUnknownTypes = legacy ^. #allowUnknownTypes,+      allowUnknownFields = True,+      idField = legacy ^. #idField,+      requireBundleVersion = Nothing,+      types = map upgradeRule (legacy ^. #types)+    }+  where+    undocumented key = FieldRule {field = key, description = Nothing, allowedValues = [], cardinality = Any, format = Nothing, elementFields = Nothing, objectFields = Nothing, reference = Nothing, path = Nothing, when = Nothing, uniqueBy = Nothing}+    upgradeRule rule =+      TypeRule+        { type_ = rule ^. #type_,+          description = Nothing,+          guidance = Nothing,+          frontmatter = emptyFrontmatterRules,+          pathPattern = rule ^. #pathPattern,+          resourceScheme = rule ^. #resourceScheme,+          requireSchemaSection = rule ^. #requireSchemaSection,+          schemaColumns = rule ^. #schemaColumns,+          idPrefix = rule ^. #idPrefix+        }++-- | Load and decode a Dhall profile descriptor from a file path. Any evaluation+-- or decoding failure is captured as a human-readable 'Left'.+--+-- The pre-nested-closure, pre-product-discovery, pre-guidance,+-- pre-nested-reference, pre-bundle-version,+-- pre-path shape, pre-actor shape, pre-object+-- shape, reference-aware shape,+-- condition-aware shape, bounded-nested shape, EP-4+-- format shape, EP-3 cardinality shape, EP-2 vocabulary shape, type-aware EP-1+-- shape, self-documenting shape, and okf 0.2.x shape are accepted by frozen+-- fallback decoders and upgraded+-- with their no-op defaults. When every decoder fails, the /current/ decoder's+-- error is reported.+loadProfileFile :: FilePath -> IO (Either Text ProfileSpec)+loadProfileFile path = do+  current <- tryDecode (Dhall.inputFile auto path)+  case current of+    Right spec -> pure (Right spec)+    -- Only the current decoder's error is kept. An author wants to know how+    -- their descriptor differs from today's schema, not from a retired one.+    Left currentError -> maybe (Left currentError) Right <$> firstFrozen frozenDecoders+  where+    -- Newest generation first. Each entry looks identical but is inferred at a+    -- distinct result type, fixed by the upgrade function it names; @auto@ then+    -- picks that generation's decoder. Adding a generation is one line here.+    frozenDecoders :: [IO (Maybe ProfileSpec)]+    frozenDecoders =+      [ attempt upgradePreNestedClosureProfileSpec,+        attempt upgradePreProductDiscoveryProfile,+        attempt upgradePreGuidanceProfile,+        attempt upgradePreNestedReferenceProfile,+        attempt upgradePreBundleVersionProfile,+        attempt upgradePrePathProfile,+        attempt upgradePreActorProfile,+        attempt upgradePreObjectProfile,+        attempt upgradeReferenceProfile,+        attempt upgradeConditionalProfile,+        attempt upgradeNestedProfile,+        attempt upgradeFormatProfile,+        attempt upgradeCardinalityProfile,+        attempt upgradeVocabularyProfile,+        attempt upgradeTypeAwareProfile,+        attempt upgradeDescribedProfile,+        attempt upgradeLegacyProfile+      ]++    -- Short-circuiting, so a descriptor that decodes at the first frozen+    -- generation costs one extra parse rather than thirteen.+    firstFrozen :: [IO (Maybe ProfileSpec)] -> IO (Maybe ProfileSpec)+    firstFrozen [] = pure Nothing+    firstFrozen (decoder : remaining) =+      decoder >>= \case+        Just spec -> pure (Just spec)+        Nothing -> firstFrozen remaining++    attempt :: (FromDhall a) => (a -> ProfileSpec) -> IO (Maybe ProfileSpec)+    attempt upgrade = either (const Nothing) (Just . upgrade) <$> tryDecode (Dhall.inputFile auto path)++    tryDecode :: IO a -> IO (Either Text a)+    tryDecode action =+      (Right <$> action)+        `catchSynchronous` \(exception :: SomeException) -> pure (Left (Text.pack (show exception)))++-- | Does an already-evaluated Dhall expression decode as a profile? Tries the+-- current schema, then the pre-nested-closure, pre-product-discovery,+-- pre-guidance, pre-nested-reference,+-- pre-bundle-version, pre-path, pre-actor, pre-object,+-- reference-aware,+-- condition-aware, bounded-nested, EP-4, EP-3, EP-2, EP-1, self-documenting, and+-- okf 0.2.x schemas, so the published @okf-profiles@ package still enumerates.+-- Uses 'Dhall.rawInput', which normalizes and runs the decoder's extractor+-- without throwing, which is what lets registry enumeration be pure.+decodeProfileExpr :: Expr Src Void -> Maybe ProfileSpec+decodeProfileExpr rawExpression =+  Dhall.rawInput Dhall.auto expression+    <|> ( if containsNestedClosureField expression+            then Nothing+            else+              fmap upgradePreNestedClosureProfileSpec (Dhall.rawInput Dhall.auto expression)+                <|> ( if containsProductDiscoveryField expression+                        then Nothing+                        else+                          fmap upgradePreProductDiscoveryProfile (Dhall.rawInput Dhall.auto expression)+                            <|> fmap upgradePreGuidanceProfile (Dhall.rawInput Dhall.auto expression)+                            <|> decodeProfilesBeforeGuidance expression+                    )+        )+  where+    expression = Dhall.Core.normalize rawExpression++-- | Inspect only nested-rule records reached through descriptor field rules.+-- The profile root has carried the same name since before nested closure.+containsNestedClosureField :: Expr Src Void -> Bool+containsNestedClosureField expression =+  any nestedClosure (frontmatters expression)+  where+    member key (Dhall.Core.RecordLit fields) =+      Dhall.Core.recordFieldValue <$> Dhall.Map.lookup key fields+    member _ _ = Nothing+    listValues (Dhall.Core.ListLit _ values) = toList values+    listValues _ = []+    frontmatters profile =+      maybeToList (member "frontmatter" profile)+        <> [ fm+           | typeValues <- maybeToList (member "types" profile),+             typeRule <- listValues typeValues,+             fm <- maybeToList (member "frontmatter" typeRule)+           ]+    nestedClosure fm =+      or+        [ Dhall.Map.member "allowUnknownFields" fields+        | listName <- ["required", "recommended", "optional"],+          rules <- maybeToList (member listName fm),+          rule <- listValues rules,+          shape <- ["elementFields", "objectFields"],+          Dhall.Core.Some nested <- maybeToList (member shape rule),+          Dhall.Core.RecordLit fields <- [nested]+        ]++-- | The generic Dhall record extractor deliberately ignores extra record+-- members. Without this guard, a value from the 0.8.0.0 generation can fall+-- through to an older decoder and silently lose nested-reference or uniqueness+-- declarations. Every non-empty 0.8.0.0 field-rule value carries at least one+-- of these post-0.7 record members, even when its value is @None@.+decodeProfilesBeforeGuidance :: Expr Src Void -> Maybe ProfileSpec+decodeProfilesBeforeGuidance expression+  | containsPost07DescriptorField expression = Nothing+  | otherwise =+      fmap upgradePreNestedReferenceProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradePreBundleVersionProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradePrePathProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradePreActorProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradePreObjectProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradeReferenceProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradeConditionalProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradeNestedProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradeFormatProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradeCardinalityProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradeVocabularyProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradeTypeAwareProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradeDescribedProfile (Dhall.rawInput Dhall.auto expression)+        <|> fmap upgradeLegacyProfile (Dhall.rawInput Dhall.auto expression)++containsPost07DescriptorField :: Expr Src Void -> Bool+containsPost07DescriptorField =+  anyOf (cosmosOf Dhall.Core.subExpressions) $ \case+    Dhall.Core.RecordLit fields ->+      any (`Dhall.Map.member` fields) ["uniqueBy", "allowLocal", "externalUriPattern"]+    _ -> False++-- | The description a profile attaches to a frontmatter key, looking in+-- @required@ first, then @recommended@, then @optional@. 'Nothing' when the key+-- is undocumented or absent from the profile entirely.+profileFieldDescription :: ProfileSpec -> Text -> Maybe Text+profileFieldDescription spec key =+  case [rule | rule <- rules, rule ^. #field == key] of+    (rule : _) -> rule ^. #description+    [] -> Nothing+  where+    rules =+      spec ^. #frontmatter . #required+        <> spec ^. #frontmatter . #recommended+        <> spec ^. #frontmatter . #optional++-- | A malformed profile definition. The optional type is absent for profile+-- scope and present for a type-specific scope. The list name is @required@,+-- @recommended@, or @optional@.+data ProfileDefinitionError+  = InvalidConceptConstraint (Maybe Text) (Maybe Text) ValueSelector Text+  | DuplicateTypeRule Text+  | DuplicateFieldRule (Maybe Text) Text Text+  | ConflictingFieldRequirement (Maybe Text) Text+  | UnsatisfiableVocabulary (Maybe Text) Text [Text] [Text]+  | ConflictingCardinality (Maybe Text) Text Cardinality Cardinality+  | ElementFieldsRequireList (Maybe Text) FieldPath Cardinality+  | InvalidFormatParameter FieldPath FieldFormat Text+  | ConflictingFieldFormat FieldPath FieldFormat FieldFormat+  | EmptyConditionValues (Maybe Text) FieldPath FieldPath+  | ConditionFieldNotDeclared (Maybe Text) FieldPath FieldPath+  | ConditionFieldNotScalar (Maybe Text) FieldPath FieldPath Cardinality+  | ConditionFieldOpenVocabulary (Maybe Text) FieldPath FieldPath+  | ConditionFieldHasUnreachableValues (Maybe Text) FieldPath FieldPath [Text] [Text]+  | SelfConditionalField (Maybe Text) FieldPath+  | InvalidReferencePrefix (Maybe Text) FieldPath Text+  | ReferencePrefixNotDeclared (Maybe Text) FieldPath Text+  | ReferenceRequiresIdField (Maybe Text) FieldPath+  | InvalidExternalReferenceScheme (Maybe Text) FieldPath Text+  | ConflictingReferencePrefix Text FieldPath Text Text+  | ReferenceWithFormat (Maybe Text) FieldPath FieldFormat+  | -- | an @optional@ rule carries a @when@ condition, which gates only presence+    -- and is therefore dead: an optional rule has no presence check at all+    OptionalFieldWithCondition (Maybe Text) FieldPath+  | -- | a rule declares @objectFields@ alongside an explicit scalar or list+    -- cardinality; an object is neither, so the pairing cannot be satisfied+    ObjectFieldsRequireObjectShape (Maybe Text) FieldPath Cardinality+  | -- | one rule declares both a document-handle policy and a path policy;+    -- a value cannot be resolved as both a handle and a path+    PathReferenceWithHandleReference (Maybe Text) FieldPath+  | InvalidExternalUriPattern (Maybe Text) FieldPath Text Text+  | ConflictingExternalUriPatterns Text FieldPath Text Text+  | UniqueByRequiresElementFields (Maybe Text) FieldPath Text+  | UniqueByFieldNotDeclared (Maybe Text) FieldPath+  | UniqueByFieldNotUnconditionallyRequired (Maybe Text) FieldPath+  | UniqueByFieldNotScalar (Maybe Text) FieldPath Cardinality+  | ConflictingUniqueBy Text FieldPath Text Text+  | -- | @okfVersion@ is not @\<major\>.\<minor\>@+    InvalidProfileOkfVersion Text+  | -- | @okfVersion@ names a major version okf does not implement, so okf cannot+    -- know which of its rules still hold+    ProfileOkfVersionNotUnderstood Text+  | -- | @requireBundleVersion@ is not @\<major\>.\<minor\>@, so no bundle+    -- declaration could ever be compared against it+    InvalidRequiredBundleVersion Text+  | -- | a required or recommended rule names a key the declared version+    -- supersedes (scope, path, declared version, version that superseded the key)+    FieldSupersededInOkfVersion (Maybe Text) FieldPath Text Text+  | -- | a rule names a value format introduced after the declared version+    -- (scope, path, format, declared version, version that introduced the format)+    FormatRequiresOkfVersion (Maybe Text) FieldPath FieldFormat Text Text+  deriving stock (Generic, Eq, Ord, Show)++-- | Whether a 'PresenceClause' demands a key or merely recommends it. There is+-- deliberately no @OptionalField@ constructor: an optional key is encoded as an+-- 'EffectiveFieldRule' with /no/ presence clauses at all.+data FieldRequirement = RecommendedField | RequiredField+  deriving stock (Generic, Eq, Ord, Show)++-- | One reason a key may have to be present, optionally gated by a condition on+-- another same-scope key. Abstract: read it with 'presenceClauseRequirement' and+-- 'presenceClauseCondition'.+data PresenceClause = PresenceClause+  { requirement :: !FieldRequirement,+    condition :: !(Maybe FieldCondition)+  }+  deriving stock (Generic, Eq, Show)++-- | Everything that actually applies to one frontmatter key for one concept+-- type: the profile-scope declaration merged with the type-scope one per+-- [ADR 5](docs/adr/5-compile-profile-rules-before-validation.md). Abstract: read+-- it with the @fieldRule*@ accessors below, never by pattern matching, so that+-- later profile features can extend it without breaking consumers.+data EffectiveFieldRule = EffectiveFieldRule+  { presenceClauses :: ![PresenceClause],+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe FieldFormat),+    elementFields :: !(Maybe (Map Text EffectiveFieldRule)),+    objectFields :: !(Maybe (Map Text EffectiveFieldRule)),+    elementAllowsUnknownFields :: !(Maybe Bool),+    objectAllowsUnknownFields :: !(Maybe Bool),+    reference :: !(Maybe HandleReferenceRule),+    path :: !(Maybe PathReferenceRule),+    uniqueBy :: !(Maybe Text),+    elementConstraints :: !EffectiveConceptConstraints,+    objectConstraints :: !EffectiveConceptConstraints,+    compiledExternalUriPattern :: !(Maybe Regex)+  }+  deriving stock (Generic)++instance Eq EffectiveFieldRule where+  left == right =+    left ^. #elementConstraints == right ^. #elementConstraints+      && left ^. #objectConstraints == right ^. #objectConstraints+      && left ^. #presenceClauses == right ^. #presenceClauses+      && left ^. #description == right ^. #description+      && left ^. #allowedValues == right ^. #allowedValues+      && left ^. #cardinality == right ^. #cardinality+      && left ^. #format == right ^. #format+      && left ^. #elementAllowsUnknownFields == right ^. #elementAllowsUnknownFields+      && left ^. #objectAllowsUnknownFields == right ^. #objectAllowsUnknownFields+      && left ^. #elementFields == right ^. #elementFields+      && left ^. #objectFields == right ^. #objectFields+      && left ^. #reference == right ^. #reference+      && left ^. #path == right ^. #path+      && left ^. #uniqueBy == right ^. #uniqueBy++instance Show EffectiveFieldRule where+  show rule =+    "EffectiveFieldRule "+      <> show+        ( rule ^. #presenceClauses,+          rule ^. #description,+          rule ^. #allowedValues,+          rule ^. #cardinality,+          rule ^. #format,+          rule ^. #elementFields,+          rule ^. #objectFields,+          rule ^. #reference,+          rule ^. #path,+          rule ^. #uniqueBy,+          rule ^. #elementAllowsUnknownFields,+          rule ^. #objectAllowsUnknownFields+        )++-- | The stable lowercase display name for a cardinality: @any@, @scalar@,+-- @list@, or @object@. These are the names the CLI prints and the names+-- generated profile documentation uses, so a reader who has seen one recognizes+-- the other. @object@ is also the word the CLI already prints for an actual+-- mapping value, so a cardinality-mismatch message reads coherently.+renderCardinalityName :: Cardinality -> Text+renderCardinalityName = \case+  Any -> "any"+  Scalar -> "scalar"+  List -> "list"+  Object -> "object"++-- | The stable display name for a named format: @rfc3339-utc@, @date@, @uri@,+-- @uri-with-scheme(SCHEME)@, @document-handle(PREFIX)@, @actor@,+-- @human-actor@, @integer@, @non-negative-integer@, or @boolean@. As with+-- 'renderCardinalityName', this vocabulary is shared between the CLI and+-- generated documentation and must not drift between them.+renderFieldFormatName :: FieldFormat -> Text+renderFieldFormatName = \case+  Rfc3339Utc -> "rfc3339-utc"+  Date -> "date"+  Uri -> "uri"+  UriWithScheme scheme -> "uri-with-scheme(" <> scheme <> ")"+  DocumentHandle prefix -> "document-handle(" <> prefix <> ")"+  Actor -> "actor"+  HumanActor -> "human-actor"+  Integer -> "integer"+  NonNegativeInteger -> "non-negative-integer"+  FiniteDecimal -> "finite-decimal"+  Boolean -> "boolean"++-- | The presence clauses that govern whether this key must be present, in the+-- order the profile declared them. An __empty list means the key is optional__:+-- it is fully validated whenever it is present and never reported when absent,+-- in any validation mode. A clause with 'RequiredField' is always checked; a+-- clause with 'RecommendedField' is checked only under+-- 'Okf.Validation.StrictAuthoring'. A clause carrying a 'FieldCondition' applies+-- only when that condition holds for the document being checked.+fieldRulePresenceClauses :: EffectiveFieldRule -> [PresenceClause]+fieldRulePresenceClauses rule = rule ^. #presenceClauses++-- | Prose documenting the key, merged across profile and type scope with+-- type-level prose winning. Purely documentary: it is never checked against a+-- document and can never produce a 'ProfileViolation'.+fieldRuleDescription :: EffectiveFieldRule -> Maybe Text+fieldRuleDescription rule = rule ^. #description++-- | The closed vocabulary of permitted textual values. An __empty list means+-- unconstrained__, not "no value is permitted".+fieldRuleAllowedValues :: EffectiveFieldRule -> [Text]+fieldRuleAllowedValues rule = rule ^. #allowedValues++-- | Whether the key must be a single value, a non-empty list, or either.+fieldRuleCardinality :: EffectiveFieldRule -> Cardinality+fieldRuleCardinality rule = rule ^. #cardinality++-- | The named textual format constraining present values, if any.+fieldRuleFormat :: EffectiveFieldRule -> Maybe FieldFormat+fieldRuleFormat rule = rule ^. #format++-- | The document-reference policy for this key, if any.+fieldRuleReference :: EffectiveFieldRule -> Maybe HandleReferenceRule+fieldRuleReference rule = rule ^. #reference++-- | The required scalar member whose values must be unique within this one+-- list of records, or 'Nothing' when no list-local key is declared.+fieldRuleUniqueBy :: EffectiveFieldRule -> Maybe Text+fieldRuleUniqueBy rule = rule ^. #uniqueBy++-- | The path-valued policy for this key, if any. Distinct from+-- 'fieldRuleReference': a handle resolves against the bundle's document-ID+-- index, a path against its concept tree. A rule never carries both — compiling+-- one that does is a 'PathReferenceWithHandleReference' definition error — so a+-- consumer can read whichever is present without disambiguating.+--+-- Unlike 'fieldRuleReference' this can be present on a rule taken from+-- 'fieldRuleElementFields' or 'fieldRuleObjectFields', because+-- @sources[].resource@ is the field the policy exists for.+fieldRulePath :: EffectiveFieldRule -> Maybe PathReferenceRule+fieldRulePath rule = rule ^. #path++-- | Rules for the flat object stored in each element of a list-valued key,+-- keyed by nested key name, or 'Nothing' when the key declares no nested shape.+-- Nested rules are depth-bounded: a nested rule never itself has element fields,+-- so 'fieldRuleElementFields' on a value taken from this map is always+-- 'Nothing'.+fieldRuleElementFields :: EffectiveFieldRule -> Maybe (Map Text EffectiveFieldRule)+fieldRuleElementFields rule = rule ^. #elementFields++-- | Rules for the members of the mapping stored at this key, keyed by member+-- name, or 'Nothing' when the key declares no object shape. Like+-- 'fieldRuleElementFields' this is depth-bounded: a value taken from this map+-- always has 'Nothing' for both nested accessors. A rule may declare both, which+-- means either spelling of the value is accepted and both are checked against+-- the same member rules.+fieldRuleObjectFields :: EffectiveFieldRule -> Maybe (Map Text EffectiveFieldRule)+fieldRuleObjectFields rule = rule ^. #objectFields++-- | Effective per-shape closure. Nothing means no rule for that shape;+-- Just False with an empty member map forbids every supplied member name.+fieldRuleElementAllowsUnknownFields :: EffectiveFieldRule -> Maybe Bool+fieldRuleElementAllowsUnknownFields rule = rule ^. #elementAllowsUnknownFields++fieldRuleObjectAllowsUnknownFields :: EffectiveFieldRule -> Maybe Bool+fieldRuleObjectAllowsUnknownFields rule = rule ^. #objectAllowsUnknownFields++-- | Whether this clause demands the key or merely recommends it.+presenceClauseRequirement :: PresenceClause -> FieldRequirement+presenceClauseRequirement clause = clause ^. #requirement++-- | The same-scope predicate gating this clause, or 'Nothing' when it always+-- applies.+presenceClauseCondition :: PresenceClause -> Maybe FieldCondition+presenceClauseCondition clause = clause ^. #condition++-- | A raw profile whose authoring contradictions have been rejected and whose+-- effective profile-plus-type frontmatter rules have been precomputed.+data CompiledProfile = CompiledProfile+  { spec :: !ProfileSpec,+    baseRules :: !(Map Text EffectiveFieldRule),+    baseConstraints :: !EffectiveConceptConstraints,+    constraintsByType :: !(Map Text EffectiveConceptConstraints),+    rulesByType :: !(Map Text (Map Text EffectiveFieldRule)),+    -- | @requireBundleVersion@ already parsed, so 'validateProfileVersion' never+    -- re-parses and cannot disagree with what compilation accepted.+    requiredBundleVersion :: !(Maybe OkfVersion)+  }+  deriving stock (Generic, Eq, Show)++compiledProfileSpec :: CompiledProfile -> ProfileSpec+compiledProfileSpec compiled = compiled ^. #spec++-- | The minimum OKF version the profile requires its bundle to declare, already+-- parsed. 'Nothing' when the profile requires nothing, which is the default and+-- the case for almost every profile.+compiledProfileRequiredBundleVersion :: CompiledProfile -> Maybe OkfVersion+compiledProfileRequiredBundleVersion compiled = compiled ^. #requiredBundleVersion++-- | The concept @type@ strings the profile declares, in the order the descriptor+-- declares them. Declaration order is the author's and is preserved because+-- documentation and display should follow it rather than an alphabetical+-- reordering.+compiledProfileTypeNames :: CompiledProfile -> [Text]+compiledProfileTypeNames compiled =+  [rule ^. #type_ | rule <- compiledProfileSpec compiled ^. #types]++-- | The rules that apply to every document, whatever its type, keyed by+-- frontmatter key name.+compiledProfileBaseRules :: CompiledProfile -> Map Text EffectiveFieldRule+compiledProfileBaseRules compiled = compiled ^. #baseRules++-- | The rules that apply to a document of the given @type@: the profile-scope+-- rules merged with that type's own. A type the profile does not declare falls+-- back to the profile-scope rules alone, because a profile with+-- @allowUnknownTypes = True@ still applies its profile-wide expectations to a+-- document whose type it does not recognize.+compiledProfileRulesForType :: CompiledProfile -> Text -> Map Text EffectiveFieldRule+compiledProfileRulesForType = effectiveRulesForType++compileProfile :: ProfileSpec -> Either (NonEmpty ProfileDefinitionError) CompiledProfile+compileProfile rawSpec =+  case definitionErrors of+    firstError : remainingErrors -> Left (firstError :| remainingErrors)+    [] ->+      Right+        CompiledProfile+          { spec = rawSpec,+            baseConstraints = resolveConstraints baseRules (frontmatterConstraints (rawSpec ^. #frontmatter)),+            constraintsByType = Map.fromList [(r ^. #type_, resolveConstraints (mergeRules baseRules (compileRules (r ^. #frontmatter))) (mergeConstraints (frontmatterConstraints (rawSpec ^. #frontmatter)) (frontmatterConstraints (r ^. #frontmatter)))) | r <- rawSpec ^. #types],+            baseRules,+            rulesByType =+              Map.fromList+                [ (rule ^. #type_, mergeRules baseRules (compileRules (rule ^. #frontmatter)))+                | rule <- rawSpec ^. #types+                ],+            -- Safe here and only here: 'requiredBundleVersionErrors' is one of+            -- the checks 'definitionErrors' collects, so reaching this branch+            -- means the value parsed.+            requiredBundleVersion = rawSpec ^. #requireBundleVersion >>= parseOkfVersion+          }+  where+    baseRules = compileRules (rawSpec ^. #frontmatter)+    typeNames = map (^. #type_) (rawSpec ^. #types)+    definitionErrors =+      List.sortOn definitionErrorKey $+        map DuplicateTypeRule (duplicates typeNames)+          <> scopeErrors Nothing (rawSpec ^. #frontmatter)+          <> concat+            [ scopeErrors (Just (rule ^. #type_)) (rule ^. #frontmatter)+            | rule <- rawSpec ^. #types+            ]+          <> constraintErrors Nothing Nothing baseRules (frontmatterConstraints (rawSpec ^. #frontmatter))+          <> concat [constraintErrors (Just (r ^. #type_)) Nothing (mergeRules baseRules (compileRules (r ^. #frontmatter))) (mergeConstraints (frontmatterConstraints (rawSpec ^. #frontmatter)) (frontmatterConstraints (r ^. #frontmatter))) | r <- rawSpec ^. #types]+          <> vocabularyErrors+          <> cardinalityErrors+          <> nestedCardinalityErrors+          <> objectCardinalityErrors+          <> formatParameterErrors+          <> conflictingFormatErrors+          <> conditionDefinitionErrors+          <> referenceDefinitionErrors+          <> uniquenessDefinitionErrors+          <> versionErrors+          <> requiredBundleVersionErrors++    definitionErrorKey = \case+      InvalidConceptConstraint scope parent sel reason -> (2, fromMaybe "" scope, 32, fromMaybe "" parent <> Text.pack (show sel), Text.length reason)+      DuplicateTypeRule ctype -> (1 :: Int, ctype, 0 :: Int, "", 0 :: Int)+      DuplicateFieldRule scope listName key ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, listKey listName, key, 0)+      ConflictingFieldRequirement scope key ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, 2, key, 0)+      UnsatisfiableVocabulary scope key _ _ ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, 3, key, 0)+      ConflictingCardinality scope key _ _ ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, 4, key, 0)+      ElementFieldsRequireList scope path cardinality ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, 4, renderFieldPathKey path, fromEnum (cardinality == Scalar))+      InvalidFormatParameter path fieldFormat parameter ->+        (2, renderFieldPathKey path, 5, Text.pack (show fieldFormat), Text.length parameter)+      ConflictingFieldFormat path profileFormat typeFormat ->+        (2, renderFieldPathKey path, 6, Text.pack (show profileFormat), fromEnum (profileFormat == typeFormat))+      EmptyConditionValues scope target source -> conditionErrorKey scope target source 7+      ConditionFieldNotDeclared scope target source -> conditionErrorKey scope target source 8+      ConditionFieldNotScalar scope target source cardinality ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, 9, renderFieldPathKey target <> ":" <> renderFieldPathKey source, fromEnum (cardinality == Scalar))+      ConditionFieldOpenVocabulary scope target source -> conditionErrorKey scope target source 10+      ConditionFieldHasUnreachableValues scope target source _ _ -> conditionErrorKey scope target source 11+      SelfConditionalField scope target ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, 12, renderFieldPathKey target, 0)+      InvalidReferencePrefix scope target prefix -> referenceErrorKey scope target 13 prefix+      ReferencePrefixNotDeclared scope target prefix -> referenceErrorKey scope target 14 prefix+      ReferenceRequiresIdField scope target -> referenceErrorKey scope target 15 ""+      InvalidExternalReferenceScheme scope target scheme -> referenceErrorKey scope target 16 scheme+      ConflictingReferencePrefix ctype target profilePrefix typePrefix ->+        (1, ctype, 17, renderFieldPathKey target <> ":" <> profilePrefix, Text.length typePrefix)+      ReferenceWithFormat scope target fieldFormat -> referenceErrorKey scope target 18 (Text.pack (show fieldFormat))+      OptionalFieldWithCondition scope target ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, 19, renderFieldPathKey target, 0)+      ObjectFieldsRequireObjectShape scope fieldPath cardinality ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, 20, renderFieldPathKey fieldPath, fromEnum (cardinality == Scalar))+      PathReferenceWithHandleReference scope target -> referenceErrorKey scope target 21 ""+      InvalidExternalUriPattern scope target patternText detail ->+        referenceErrorKey scope target 22 (patternText <> ":" <> detail)+      ConflictingExternalUriPatterns ctype target profilePattern typePattern ->+        (1, ctype, 23, renderFieldPathKey target <> ":" <> profilePattern, Text.length typePattern)+      UniqueByRequiresElementFields scope target key -> uniqueErrorKey scope target 24 key+      UniqueByFieldNotDeclared scope target -> uniqueErrorKey scope target 25 ""+      UniqueByFieldNotUnconditionallyRequired scope target -> uniqueErrorKey scope target 26 ""+      UniqueByFieldNotScalar scope target cardinality -> uniqueErrorKey scope target 27 (Text.pack (show cardinality))+      ConflictingUniqueBy ctype target profileKey typeKey ->+        (1, ctype, 28, renderFieldPathKey target <> ":" <> profileKey, Text.length typeKey)+      -- The two version-parse errors are profile-wide rather than scoped, and+      -- rank below every scope rank: if the declared version is unreadable, every+      -- version-derived error below is downstream noise and the reader should see+      -- the cause first. Nothing constrains the first component to be+      -- non-negative.+      InvalidProfileOkfVersion rawVersion -> (-1, rawVersion, 0, "", 0)+      ProfileOkfVersionNotUnderstood rawVersion -> (-1, rawVersion, 1, "", 0)+      InvalidRequiredBundleVersion rawVersion -> (-1, rawVersion, 2, "", 0)+      FieldSupersededInOkfVersion scope path _declared supersededIn ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, 30, renderFieldPathKey path <> ":" <> supersededIn, 0)+      FormatRequiresOkfVersion scope path fieldFormat _declared introducedIn ->+        let (scopeRank, typeName) = scopeKey scope+         in (scopeRank, typeName, 31, renderFieldPathKey path <> ":" <> introducedIn, Text.length (Text.pack (show fieldFormat)))++    scopeKey Nothing = (0, "")+    scopeKey (Just ctype) = (1, ctype)+    listKey "required" = 0+    listKey _ = 1+    conditionErrorKey scope target source rank =+      let (scopeRank, typeName) = scopeKey scope+       in (scopeRank, typeName, rank, renderFieldPathKey target <> ":" <> renderFieldPathKey source, 0)+    referenceErrorKey scope target rank detail =+      let (scopeRank, typeName) = scopeKey scope+       in (scopeRank, typeName, rank, renderFieldPathKey target <> ":" <> detail, 0)+    uniqueErrorKey = referenceErrorKey++    scopeErrors scope FrontmatterRules {required, recommended, optional} =+      [DuplicateFieldRule scope "required" key | key <- duplicates (map (^. #field) required)]+        <> [DuplicateFieldRule scope "recommended" key | key <- duplicates (map (^. #field) recommended)]+        <> [DuplicateFieldRule scope "optional" key | key <- duplicates (map (^. #field) optional)]+        <> [ ConflictingFieldRequirement scope key+           | key <- presenceListCollisions (map (^. #field) required) (map (^. #field) recommended) (map (^. #field) optional)+           ]+        <> concatMap (nestedScopeErrors scope) (required <> recommended <> optional)++    nestedScopeErrors scope parentRule =+      concatMap oneNestedRuleSet (declaredNestedRuleSets parentRule)+      where+        oneNestedRuleSet NestedRules {required, recommended, optional} =+          let qualify key = parentRule ^. #field <> "." <> key+           in [DuplicateFieldRule scope "nested required" (qualify key) | key <- duplicates (map (^. #field) required)]+                <> [DuplicateFieldRule scope "nested recommended" (qualify key) | key <- duplicates (map (^. #field) recommended)]+                <> [DuplicateFieldRule scope "nested optional" (qualify key) | key <- duplicates (map (^. #field) optional)]+                <> [ ConflictingFieldRequirement scope (qualify key)+                   | key <- presenceListCollisions (map (^. #field) required) (map (^. #field) recommended) (map (^. #field) optional)+                   ]++    -- One key classified by more than one presence list at a single scope. The+    -- profile cannot say both "always check for this" and "never check for+    -- this", so any pairing is a definition error rather than a precedence rule.+    presenceListCollisions requiredKeys recommendedKeys optionalKeys =+      List.nub . List.sort . concat $+        [ List.intersect requiredKeys recommendedKeys,+          List.intersect requiredKeys optionalKeys,+          List.intersect recommendedKeys optionalKeys+        ]++    duplicates = mapMaybe duplicateHead . List.group . List.sort+    duplicateHead (candidate : _ : _) = Just candidate+    duplicateHead _ = Nothing++    vocabularyErrors =+      [ UnsatisfiableVocabulary (Just (rule ^. #type_)) key profileValues typeValues+      | rule <- rawSpec ^. #types,+        let typeRules = compileRules (rule ^. #frontmatter),+        (key, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),+        let profileValues = profileRule ^. #allowedValues+            typeValues = typeRule ^. #allowedValues,+        not (null profileValues),+        not (null typeValues),+        null (mergeVocabulary profileValues typeValues)+      ]+        <> [ UnsatisfiableVocabulary (Just (rule ^. #type_)) (parentKey <> "." <> nestedKey) profileValues typeValues+           | rule <- rawSpec ^. #types,+             let typeRules = compileRules (rule ^. #frontmatter),+             (parentKey, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),+             (profileNested, typeNested) <- pairedNestedRuleMaps profileRule typeRule,+             (nestedKey, (profileNestedRule, typeNestedRule)) <- Map.toAscList (Map.intersectionWith (,) profileNested typeNested),+             let profileValues = profileNestedRule ^. #allowedValues+                 typeValues = typeNestedRule ^. #allowedValues,+             not (null profileValues),+             not (null typeValues),+             null (mergeVocabulary profileValues typeValues)+           ]++    cardinalityErrors =+      [ ConflictingCardinality (Just (rule ^. #type_)) key profileCardinality typeCardinality+      | rule <- rawSpec ^. #types,+        let typeRules = compileRules (rule ^. #frontmatter),+        (key, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),+        let profileCardinality = profileRule ^. #cardinality+            typeCardinality = typeRule ^. #cardinality,+        profileCardinality /= Any,+        typeCardinality /= Any,+        profileCardinality /= typeCardinality+      ]+        <> [ ConflictingCardinality (Just (rule ^. #type_)) (parentKey <> "." <> nestedKey) profileCardinality typeCardinality+           | rule <- rawSpec ^. #types,+             let typeRules = compileRules (rule ^. #frontmatter),+             (parentKey, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),+             (profileNested, typeNested) <- pairedNestedRuleMaps profileRule typeRule,+             (nestedKey, (profileNestedRule, typeNestedRule)) <- Map.toAscList (Map.intersectionWith (,) profileNested typeNested),+             let profileCardinality = profileNestedRule ^. #cardinality+                 typeCardinality = typeNestedRule ^. #cardinality,+             profileCardinality /= Any,+             typeCardinality /= Any,+             profileCardinality /= typeCardinality+           ]++    nestedCardinalityErrors =+      [ ElementFieldsRequireList scope (topLevelFieldPath (fieldRule ^. #field)) Scalar+      | (scope, rules) <- scopedFrontmatterRules,+        fieldRule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,+        isJust (fieldRule ^. #elementFields),+        fieldRule ^. #cardinality == Scalar+      ]++    -- The mirror image: @objectFields@ says the value is a mapping, and neither+    -- an explicit @scalar@ nor an explicit @list@ can be one.+    objectCardinalityErrors =+      [ ObjectFieldsRequireObjectShape scope (topLevelFieldPath (fieldRule ^. #field)) declared+      | (scope, rules) <- scopedFrontmatterRules,+        fieldRule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,+        isJust (fieldRule ^. #objectFields),+        let declared = fieldRule ^. #cardinality,+        declared == Scalar || declared == List+      ]++    scopedFrontmatterRules =+      (Nothing, rawSpec ^. #frontmatter)+        : [(Just (rule ^. #type_), rule ^. #frontmatter) | rule <- rawSpec ^. #types]++    -- The nested rule sets one raw rule declares: its list-element rules, its+    -- object-member rules, or both. Deduplicated because @mk.recordOrList@+    -- deliberately declares the same rules under both names, and a definition+    -- error names a path such as @verified.by@ that does not distinguish the two+    -- — so without this the same incoherence would be reported twice.+    declaredNestedRuleSets rawRule =+      List.nub (catMaybes [rawRule ^. #elementFields, rawRule ^. #objectFields])++    -- The same idea across two scopes: the nested maps a profile-scope rule and+    -- a type-scope rule both declare, paired shape with matching shape. Pairing+    -- an element map against an object map would compare rules that never meet.+    pairedNestedRuleMaps profileRule typeRule =+      List.nub+        [ (profileNested, typeNested)+        | nestedMap <- [(^. #elementFields), (^. #objectFields)],+          Just profileNested <- [nestedMap profileRule],+          Just typeNested <- [nestedMap typeRule]+        ]++    formatParameterErrors =+      [ InvalidFormatParameter (topLevelFieldPath (rule ^. #field)) fieldFormat parameter+      | rules <- (rawSpec ^. #frontmatter) : map (^. #frontmatter) (rawSpec ^. #types),+        rule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,+        Just (fieldFormat, parameter) <- [invalidFormatParameter =<< rule ^. #format]+      ]+        <> [ InvalidFormatParameter (nestedDefinitionPath (rule ^. #field) (nestedRule ^. #field)) fieldFormat parameter+           | rules <- (rawSpec ^. #frontmatter) : map (^. #frontmatter) (rawSpec ^. #types),+             rule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,+             nestedRules <- declaredNestedRuleSets rule,+             nestedRule <- nestedRules ^. #required <> nestedRules ^. #recommended <> nestedRules ^. #optional,+             Just (fieldFormat, parameter) <- [invalidFormatParameter =<< nestedRule ^. #format]+           ]++    conflictingFormatErrors =+      [ ConflictingFieldFormat (topLevelFieldPath key) profileFormat typeFormat+      | rule <- rawSpec ^. #types,+        let typeRules = compileRules (rule ^. #frontmatter),+        (key, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),+        Just profileFormat <- [profileRule ^. #format],+        Just typeFormat <- [typeRule ^. #format],+        mergeFieldFormat (Just profileFormat) (Just typeFormat) == Nothing+      ]+        <> [ ConflictingFieldFormat (nestedDefinitionPath parentKey nestedKey) profileFormat typeFormat+           | rule <- rawSpec ^. #types,+             let typeRules = compileRules (rule ^. #frontmatter),+             (parentKey, (profileRule, typeRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),+             (profileNested, typeNested) <- pairedNestedRuleMaps profileRule typeRule,+             (nestedKey, (profileNestedRule, typeNestedRule)) <- Map.toAscList (Map.intersectionWith (,) profileNested typeNested),+             Just profileFormat <- [profileNestedRule ^. #format],+             Just typeFormat <- [typeNestedRule ^. #format],+             mergeFieldFormat (Just profileFormat) (Just typeFormat) == Nothing+           ]++    conditionDefinitionErrors =+      conditionErrors Nothing Nothing (rawSpec ^. #frontmatter) baseRules+        <> concat+          [ let typeRules = compileRules (rule ^. #frontmatter)+                mergedRules = mergeRules baseRules typeRules+             in conditionErrors (Just (rule ^. #type_)) Nothing (rule ^. #frontmatter) mergedRules+          | rule <- rawSpec ^. #types+          ]++    conditionErrors scope parent rules effectiveRules =+      concatMap (fieldConditionErrors scope parent effectiveRules) (rules ^. #required <> rules ^. #recommended)+        <> [ deadCondition scope parent (rawRule ^. #field)+           | rawRule <- rules ^. #optional,+             isJust (rawRule ^. #when)+           ]+        <> List.nub+          ( concat+              [ concatMap+                  (fieldConditionErrors scope (Just (rawRule ^. #field)) effectiveNestedRules)+                  (nestedRules ^. #required <> nestedRules ^. #recommended)+                  <> [ deadCondition scope (Just (rawRule ^. #field)) (nestedRule ^. #field)+                     | nestedRule <- nestedRules ^. #optional,+                       isJust (nestedRule ^. #when)+                     ]+              | rawRule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,+                let effectiveRule = Map.lookup (rawRule ^. #field) effectiveRules,+                (nestedRules, effectiveNestedRules) <-+                  catMaybes+                    [ (,) <$> (rawRule ^. #elementFields) <*> (effectiveRule >>= (^. #elementFields)),+                      (,) <$> (rawRule ^. #objectFields) <*> (effectiveRule >>= (^. #objectFields))+                    ]+              ]+          )++    -- A condition gates presence, and an optional rule has no presence clause to+    -- gate, so the pairing is dead in the descriptor rather than a weaker rule.+    deadCondition scope parent key =+      OptionalFieldWithCondition+        scope+        (maybe (topLevelFieldPath key) (\parentKey -> nestedDefinitionPath parentKey key) parent)++    fieldConditionErrors scope parent effectiveRules rawRule =+      case rawRule ^. #when of+        Nothing -> []+        Just FieldCondition {field = sourceKey, hasValue = conditionValues} ->+          let targetKey = rawRule ^. #field+              targetPath = maybe (topLevelFieldPath targetKey) (\parentKey -> nestedDefinitionPath parentKey targetKey) parent+              sourcePath = maybe (topLevelFieldPath sourceKey) (\parentKey -> nestedDefinitionPath parentKey sourceKey) parent+              normalizedValues = deduplicate conditionValues+              sourceErrors =+                case Map.lookup sourceKey effectiveRules of+                  Nothing -> [ConditionFieldNotDeclared scope targetPath sourcePath]+                  Just sourceRule ->+                    [ ConditionFieldNotScalar scope targetPath sourcePath (sourceRule ^. #cardinality)+                    | sourceRule ^. #cardinality /= Scalar+                    ]+                      <> [ ConditionFieldOpenVocabulary scope targetPath sourcePath+                         | null (sourceRule ^. #allowedValues)+                         ]+                      <> let unreachable = filter (`notElem` sourceRule ^. #allowedValues) normalizedValues+                          in [ ConditionFieldHasUnreachableValues scope targetPath sourcePath unreachable (sourceRule ^. #allowedValues)+                             | not (null (sourceRule ^. #allowedValues)),+                               not (null unreachable)+                             ]+           in [EmptyConditionValues scope targetPath sourcePath | null normalizedValues]+                <> [SelfConditionalField scope targetPath | targetKey == sourceKey]+                <> sourceErrors++    referenceDefinitionErrors =+      List.nub $+        concatMap rawReferenceErrors scopedRules+          <> concatMap mergedReferenceErrors (rawSpec ^. #types)+      where+        declaredPrefixes = mapMaybe (^. #idPrefix) (rawSpec ^. #types)+        scopedRules =+          (Nothing, rawSpec ^. #frontmatter)+            : [(Just (rule ^. #type_), rule ^. #frontmatter) | rule <- rawSpec ^. #types]++        rawReferenceErrors (scope, rules) =+          concatMap topLevelPolicyErrors topLevelRules+            <> [ nestedError+               | rule <- topLevelRules,+                 nestedRules <- declaredNestedRuleSets rule,+                 nestedRule <- nestedRules ^. #required <> nestedRules ^. #recommended <> nestedRules ^. #optional,+                 nestedError <- policyErrors scope (nestedDefinitionPath (rule ^. #field) (nestedRule ^. #field)) (nestedRule ^. #format) (nestedRule ^. #reference) (nestedRule ^. #path)+               ]+          where+            topLevelRules = rules ^. #required <> rules ^. #recommended <> rules ^. #optional+            topLevelPolicyErrors rule =+              policyErrors scope (topLevelFieldPath (rule ^. #field)) (rule ^. #format) (rule ^. #reference) (rule ^. #path)++        policyErrors scope path declaredFormat handlePolicy pathPolicy =+          referencePolicyErrors scope path declaredFormat handlePolicy+            <> pathPolicyErrors scope path declaredFormat handlePolicy pathPolicy++        referencePolicyErrors scope path declaredFormat = \case+          Nothing -> []+          Just policy ->+            let prefix = policy ^. #localPrefix+                schemes = deduplicateSchemes (policy ^. #externalUriSchemes)+             in [InvalidReferencePrefix scope path prefix | not (validDocumentHandlePrefix prefix)]+                  <> [ReferencePrefixNotDeclared scope path prefix | prefix `notElem` declaredPrefixes]+                  <> [ReferenceRequiresIdField scope path | isNothing (rawSpec ^. #idField)]+                  <> [InvalidExternalReferenceScheme scope path scheme | scheme <- schemes, not (validUriScheme scheme)]+                  <> [ReferenceWithFormat scope path fieldFormat | Just fieldFormat <- [declaredFormat]]+                  <> [ InvalidExternalUriPattern scope path patternText detail+                     | Just patternText <- [policy ^. #externalUriPattern],+                       Left detail <- [compileExternalUriPattern patternText]+                     ]++        -- The three ways a path policy can be incoherent on its own. Two reuse+        -- the handle-reference constructors because the claim is identical: a+        -- scheme that is not a legal URI scheme, and a structural interpretation+        -- of a value paired with a textual format that would be checked against+        -- the same text. The third is genuinely new — a value cannot be resolved+        -- as both a @PREFIX-N@ handle and a §6.2 path — and cannot arise at+        -- nested scope, where 'NestedFieldRule' carries no handle policy.+        pathPolicyErrors scope path declaredFormat handlePolicy = \case+          Nothing -> []+          Just policy ->+            [ InvalidExternalReferenceScheme scope path scheme+            | scheme <- deduplicateSchemes (policy ^. #externalUriSchemes),+              not (validUriScheme scheme)+            ]+              <> [ReferenceWithFormat scope path fieldFormat | Just fieldFormat <- [declaredFormat]]+              <> [PathReferenceWithHandleReference scope path | isJust handlePolicy]++        mergedReferenceErrors typeRule =+          [ ConflictingReferencePrefix (typeRule ^. #type_) path (profilePolicy ^. #localPrefix) (typePolicy ^. #localPrefix)+          | (path, profileRule, typeFieldRule) <- pairedRules typeRule,+            Just profilePolicy <- [profileRule ^. #reference],+            Just typePolicy <- [typeFieldRule ^. #reference],+            profilePolicy ^. #localPrefix /= typePolicy ^. #localPrefix+          ]+            <> [ ConflictingExternalUriPatterns (typeRule ^. #type_) path profilePattern typePattern+               | (path, profileRule, typeFieldRule) <- pairedRules typeRule,+                 Just profilePattern <- [profileRule ^. #reference >>= (^. #externalUriPattern)],+                 Just typePattern <- [typeFieldRule ^. #reference >>= (^. #externalUriPattern)],+                 profilePattern /= typePattern+               ]+            <> [ ReferenceWithFormat (Just (typeRule ^. #type_)) path fieldFormat+               | (path, profileRule, typeFieldRule) <- pairedRules typeRule,+                 (referenceRule, formatRule) <- [(profileRule, typeFieldRule), (typeFieldRule, profileRule)],+                 isJust (referenceRule ^. #reference),+                 Just fieldFormat <- [formatRule ^. #format]+               ]+            <> [ PathReferenceWithHandleReference (Just (typeRule ^. #type_)) path+               | (path, profileRule, typeFieldRule) <- pairedRules typeRule,+                 (referenceRule, pathRule) <- [(profileRule, typeFieldRule), (typeFieldRule, profileRule)],+                 isJust (referenceRule ^. #reference),+                 isJust (pathRule ^. #path)+               ]++        pairedRules typeRule =+          [ (topLevelFieldPath key, profileRule, typeFieldRule)+          | let typeFields = compileRules (typeRule ^. #frontmatter),+            (key, (profileRule, typeFieldRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeFields)+          ]+            <> [ (nestedDefinitionPath parentKey nestedKey, profileNestedRule, typeNestedRule)+               | let typeFields = compileRules (typeRule ^. #frontmatter),+                 (parentKey, (profileRule, typeFieldRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeFields),+                 (profileNested, typeNested) <- pairedNestedRuleMaps profileRule typeFieldRule,+                 (nestedKey, (profileNestedRule, typeNestedRule)) <- Map.toAscList (Map.intersectionWith (,) profileNested typeNested)+               ]++    uniquenessDefinitionErrors =+      concatMap (validateDeclarations Nothing baseRules) [rawSpec ^. #frontmatter]+        <> concat+          [ let typeRules = compileRules (typeRule ^. #frontmatter)+             in validateDeclarations (Just (typeRule ^. #type_)) (mergeRules baseRules typeRules) (typeRule ^. #frontmatter)+          | typeRule <- rawSpec ^. #types+          ]+        <> [ ConflictingUniqueBy (typeRule ^. #type_) (topLevelFieldPath key) profileKey typeKey+           | typeRule <- rawSpec ^. #types,+             let typeRules = compileRules (typeRule ^. #frontmatter),+             (key, (profileRule, typeFieldRule)) <- Map.toAscList (Map.intersectionWith (,) baseRules typeRules),+             Just profileKey <- [profileRule ^. #uniqueBy],+             Just typeKey <- [typeFieldRule ^. #uniqueBy],+             profileKey /= typeKey+           ]+      where+        validateDeclarations scope effectiveRules rules =+          concatMap (validateDeclaration scope effectiveRules) (rules ^. #required <> rules ^. #recommended <> rules ^. #optional)++        validateDeclaration scope effectiveRules rawRule =+          case rawRule ^. #uniqueBy of+            Nothing -> []+            Just requestedKey ->+              let parentPath = topLevelFieldPath (rawRule ^. #field)+                  memberPath = nestedDefinitionPath (rawRule ^. #field) requestedKey+               in case Map.lookup (rawRule ^. #field) effectiveRules >>= (^. #elementFields) of+                    Nothing -> [UniqueByRequiresElementFields scope parentPath requestedKey]+                    Just memberRules ->+                      case Map.lookup requestedKey memberRules of+                        Nothing -> [UniqueByFieldNotDeclared scope memberPath]+                        Just memberRule ->+                          [ UniqueByFieldNotUnconditionallyRequired scope memberPath+                          | not (any unconditionalRequired (memberRule ^. #presenceClauses))+                          ]+                            <> [ UniqueByFieldNotScalar scope memberPath (memberRule ^. #cardinality)+                               | memberRule ^. #cardinality /= Scalar+                               ]++        unconditionalRequired clause =+          clause ^. #requirement == RequiredField && isNothing (clause ^. #condition)++    -- Only a value okf cannot parse is rejected. An unknown /major/ is+    -- deliberately accepted, unlike in @okfVersion@: there the profile is asking+    -- okf to interpret rules it may not understand, while here it is stating a+    -- minimum that a bundle's own declaration is compared against, which stays+    -- meaningful whatever the major is.+    requiredBundleVersionErrors =+      case rawSpec ^. #requireBundleVersion of+        Just rawVersion+          | isNothing (parseOkfVersion rawVersion) -> [InvalidRequiredBundleVersion rawVersion]+        _ -> []++    versionErrors =+      case effectiveProfileVersion (rawSpec ^. #okfVersion) of+        Left versionError -> [versionError]+        Right effectiveVersion ->+          let atLeastV02 = effectiveVersion >= okfVersion02+              v02Text = renderOkfVersion okfVersion02+              -- The /effective/ version, not the raw declared string: a profile+              -- declaring 0.9 is checked as 0.2 and its diagnostics should say so+              -- rather than repeating a number okf did not act on.+              declaredText = renderOkfVersion effectiveVersion+           in -- A key v0.2 superseded, demanded by a profile declaring v0.2 or+              -- later. Deliberately /not/ checked in the optional list: a team+              -- migrating a corpus wants @generated@ required and @timestamp@+              -- tolerated but not demanded, and the optional list says exactly+              -- that. This is the one check whose answer depends on which presence+              -- list a rule came from, so it reads the raw lists rather than the+              -- compiled map, which erases the distinction into presence clauses.+              [ FieldSupersededInOkfVersion scope (topLevelFieldPath (rule ^. #field)) declaredText v02Text+              | atLeastV02,+                (scope, rules) <- scopedFrontmatterRules,+                rule <- rules ^. #required <> rules ^. #recommended,+                rule ^. #field `elem` fieldsSupersededInV02+              ]+                -- The actor formats encode the specification §7 convention that+                -- v0.2 introduced. A format is an okf descriptor feature rather+                -- than a key name, so unlike the mirror case below it has no+                -- house-convention reading: @FieldFormat.Actor@ /is/ §7.+                <> [ FormatRequiresOkfVersion scope path fieldFormat declaredText v02Text+                   | not atLeastV02,+                     (scope, path, fieldFormat) <- scopedFormats,+                     fieldFormat `elem` [Actor, HumanActor]+                   ]++    -- There is deliberately no mirror check, "a profile declaring v0.1 names a+    -- key v0.2 introduced", which is why 'fieldsIntroducedInV02' is unused here.+    -- A profile key /name/ does not imply the OKF core key of that name: per+    -- docs/adr/1-profile-declared-document-ids.md, constraining keys the core+    -- format does not own is what profiles are for, and @status@, @sources@, and+    -- @verified@ are ordinary words teams were already using as house conventions+    -- before v0.2 claimed them. Such a check is both retroactive and ambiguous,+    -- which docs/adr/11-growing-the-profile-descriptor-language.md forbids.++    -- Every declared format paired with the path it sits at, top-level first and+    -- then nested. Only the format checks descend: 'fieldsIntroducedInV02' and+    -- 'fieldsSupersededInV02' name /concept-level/ frontmatter keys, so matching+    -- them against a member of a record would reject a profile whose element+    -- happens to be called @status@ for having a v0.2 key it does not have.+    scopedFormats =+      [ (scope, topLevelFieldPath (rule ^. #field), fieldFormat)+      | (scope, rules) <- scopedFrontmatterRules,+        rule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,+        Just fieldFormat <- [rule ^. #format]+      ]+        <> List.nub+          [ (scope, nestedDefinitionPath (rule ^. #field) (nestedRule ^. #field), fieldFormat)+          | (scope, rules) <- scopedFrontmatterRules,+            rule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional,+            nestedRules <- declaredNestedRuleSets rule,+            nestedRule <- nestedRules ^. #required <> nestedRules ^. #recommended <> nestedRules ^. #optional,+            Just fieldFormat <- [nestedRule ^. #format]+          ]++    renderFieldPathKey (FieldPath (firstSegment :| remainingSegments)) =+      Text.intercalate "." (map renderSegment (firstSegment : remainingSegments))+    renderSegment (FieldName name) = name+    renderSegment (ArrayIndex elementIndex) = Text.pack (show elementIndex)++-- | The OKF version that introduced the v0.2 frontmatter families and the actor+-- convention. Written out rather than reusing 'supportedOkfVersion', which+-- happens to equal it today: one is "what okf implements" and the other is "what+-- introduced these keys", and they will diverge at the next minor bump.+okfVersion02 :: OkfVersion+okfVersion02 = OkfVersion {okfVersionMajor = 0, okfVersionMinor = 2}++-- | The OKF version a profile's rules are checked against, or why okf cannot+-- tell.+--+-- A higher /minor/ within a known major is clamped, mirroring+-- 'Okf.Validation.versionGate': specification §12 defines a minor bump as+-- backward-compatible additions, so every rule a v0.3 profile can express is one+-- okf already understands.+--+-- An unknown /major/ is deliberately an error, where the bundle side reads+-- best-effort — this is a considered divergence, not an oversight. §12's+-- best-effort instruction is about bundles, which may come from a third party+-- okf cannot ask. A profile is not a document okf is asked to read; it is an+-- instruction to okf about what to check, written by an author who is present.+-- Silently ignoring an instruction okf cannot interpret is worse than saying so.+-- See @docs\/adr\/10-okf-version-declaration-and-best-effort-reading.md@.+effectiveProfileVersion :: Text -> Either ProfileDefinitionError OkfVersion+effectiveProfileVersion rawVersion =+  case parseOkfVersion rawVersion of+    Nothing -> Left (InvalidProfileOkfVersion rawVersion)+    Just declared+      | okfVersionMajor declared == okfVersionMajor supportedOkfVersion ->+          Right (min declared supportedOkfVersion)+      | otherwise -> Left (ProfileOkfVersionNotUnderstood rawVersion)++compileRules :: FrontmatterRules -> Map Text EffectiveFieldRule+compileRules FrontmatterRules {required, recommended, optional} =+  Map.fromList+    ( [ (rule ^. #field, compileFieldRule RequiredField rule)+      | rule <- required+      ]+        <> [ (rule ^. #field, compileFieldRule RecommendedField rule)+           | rule <- recommended+           ]+        <> [ (rule ^. #field, compileOptionalFieldRule rule)+           | rule <- optional+           ]+    )++-- | Compile a rule the profile documents but never demands. It carries no+-- presence clause, so 'applicablePresenceClause' can never find one to report in+-- either validation mode, while every value check still runs from the+-- present-value branch. This is also the value constraints a required or+-- recommended rule is built from.+compileOptionalFieldRule :: FieldRule -> EffectiveFieldRule+compileOptionalFieldRule rule =+  normalizeRecordShapes $+    EffectiveFieldRule+      { presenceClauses = [],+        description = rule ^. #description,+        allowedValues = deduplicate (rule ^. #allowedValues),+        cardinality =+          -- Declaring a nested shape and no explicit cardinality refines what the+          -- value may be, because the shape only makes sense against one. A rule+          -- declaring both shapes stays 'Any', which is what lets either spelling+          -- of the OKF v0.2 @verified@ key satisfy it.+          case (rule ^. #objectFields, rule ^. #elementFields, rule ^. #cardinality) of+            (Just _, Just _, Any) -> Any+            (Just _, Nothing, Any) -> Object+            (Nothing, Just _, Any) -> List+            (_, _, Any) -> refineCardinalityForFormat (rule ^. #format)+            (_, _, declared) -> declared,+        format = rule ^. #format,+        elementConstraints = maybe emptyConstraints (\n -> resolveConstraints (compileNestedRules n) (nestedConstraints n)) (rule ^. #elementFields),+        objectConstraints = maybe emptyConstraints (\n -> resolveConstraints (compileNestedRules n) (nestedConstraints n)) (rule ^. #objectFields),+        elementAllowsUnknownFields = (^. #allowUnknownFields) <$> rule ^. #elementFields,+        objectAllowsUnknownFields = (^. #allowUnknownFields) <$> rule ^. #objectFields,+        elementFields = compileNestedRules <$> rule ^. #elementFields,+        objectFields = compileNestedRules <$> rule ^. #objectFields,+        reference = compiledReference,+        path = compilePathRule <$> rule ^. #path,+        uniqueBy = rule ^. #uniqueBy,+        compiledExternalUriPattern = compileReferenceMatcher compiledReference+      }+  where+    compiledReference = compileReferenceRule <$> rule ^. #reference++-- | The cardinality a rule with no declared one takes from its format.+--+-- A non-textual format implies a scalar, and without this the rule would be+-- useless: the 'Any' cardinality routes presence through 'legacyValueIsPresent',+-- which counts only non-empty text and non-empty arrays, so a @usage_count:+-- 5000@ is reported /missing/ before its value is ever examined. Refining here+-- rather than widening 'legacyValueIsPresent' keeps the meaning of every+-- descriptor that already exists — in particular a key whose value is @false@+-- keeps being reported as missing when no rule says otherwise.+--+-- An explicitly declared cardinality always wins, including @list@: a list of+-- integers is a coherent thing to demand, so pairing a numeric format with+-- 'List' is left alone rather than made an error.+refineCardinalityForFormat :: Maybe FieldFormat -> Cardinality+refineCardinalityForFormat = \case+  Just Integer -> Scalar+  Just NonNegativeInteger -> Scalar+  Just FiniteDecimal -> Scalar+  Just Boolean -> Scalar+  _ -> Any++compileFieldRule :: FieldRequirement -> FieldRule -> EffectiveFieldRule+compileFieldRule requirement rule =+  (compileOptionalFieldRule rule)+    { presenceClauses = [PresenceClause requirement (compileCondition <$> rule ^. #when)]+    }++compileNestedRules :: NestedRules -> Map Text EffectiveFieldRule+compileNestedRules NestedRules {required, recommended, optional} =+  Map.fromList+    ( [ (rule ^. #field, compileNestedFieldRule RequiredField rule)+      | rule <- required+      ]+        <> [ (rule ^. #field, compileNestedFieldRule RecommendedField rule)+           | rule <- recommended+           ]+        <> [ (rule ^. #field, compileOptionalNestedFieldRule rule)+           | rule <- optional+           ]+    )++-- | The nested counterpart of 'compileOptionalFieldRule'.+compileOptionalNestedFieldRule :: NestedFieldRule -> EffectiveFieldRule+compileOptionalNestedFieldRule rule =+  EffectiveFieldRule+    { presenceClauses = [],+      description = rule ^. #description,+      allowedValues = deduplicate (rule ^. #allowedValues),+      cardinality =+        case rule ^. #cardinality of+          Any -> refineCardinalityForFormat (rule ^. #format)+          declared -> declared,+      format = rule ^. #format,+      elementConstraints = emptyConstraints,+      objectConstraints = emptyConstraints,+      elementAllowsUnknownFields = Nothing,+      objectAllowsUnknownFields = Nothing,+      elementFields = Nothing,+      -- Nested rules stay depth-bounded: 'NestedFieldRule' has no object member,+      -- so a profile cannot constrain @sources[0].usage_window.from@.+      objectFields = Nothing,+      reference = compiledReference,+      -- But it does carry a path policy, which is the point of the member —+      -- @sources[].resource@ is only reachable here.+      path = compilePathRule <$> rule ^. #path,+      uniqueBy = Nothing,+      compiledExternalUriPattern = compileReferenceMatcher compiledReference+    }+  where+    compiledReference = compileReferenceRule <$> rule ^. #reference++compileNestedFieldRule :: FieldRequirement -> NestedFieldRule -> EffectiveFieldRule+compileNestedFieldRule requirement rule =+  (compileOptionalNestedFieldRule rule)+    { presenceClauses = [PresenceClause requirement (compileCondition <$> rule ^. #when)]+    }++mergeRules :: Map Text EffectiveFieldRule -> Map Text EffectiveFieldRule -> Map Text EffectiveFieldRule+mergeRules = Map.unionWith mergeEffectiveFieldRule++mergeEffectiveFieldRule :: EffectiveFieldRule -> EffectiveFieldRule -> EffectiveFieldRule+mergeEffectiveFieldRule profileRule typeRule =+  normalizeRecordShapes $+    EffectiveFieldRule+      { presenceClauses = profileRule ^. #presenceClauses <> typeRule ^. #presenceClauses,+        description = typeRule ^. #description <|> profileRule ^. #description,+        allowedValues = mergeVocabulary (profileRule ^. #allowedValues) (typeRule ^. #allowedValues),+        cardinality = mergeCardinality (profileRule ^. #cardinality) (typeRule ^. #cardinality),+        format = fromMaybe (profileRule ^. #format) (mergeFieldFormat (profileRule ^. #format) (typeRule ^. #format)),+        elementConstraints = resolveConstraints (fromMaybe Map.empty (mergeNestedRuleMaps (profileRule ^. #elementFields) (typeRule ^. #elementFields))) (mergeConstraints (profileRule ^. #elementConstraints) (typeRule ^. #elementConstraints)),+        objectConstraints = resolveConstraints (fromMaybe Map.empty (mergeNestedRuleMaps (profileRule ^. #objectFields) (typeRule ^. #objectFields))) (mergeConstraints (profileRule ^. #objectConstraints) (typeRule ^. #objectConstraints)),+        elementAllowsUnknownFields = mergeClosure (profileRule ^. #elementAllowsUnknownFields) (typeRule ^. #elementAllowsUnknownFields),+        objectAllowsUnknownFields = mergeClosure (profileRule ^. #objectAllowsUnknownFields) (typeRule ^. #objectAllowsUnknownFields),+        elementFields = mergeNestedRuleMaps (profileRule ^. #elementFields) (typeRule ^. #elementFields),+        objectFields = mergeNestedRuleMaps (profileRule ^. #objectFields) (typeRule ^. #objectFields),+        reference = mergedReference,+        path = mergePathRule (profileRule ^. #path) (typeRule ^. #path),+        uniqueBy = fromMaybe (profileRule ^. #uniqueBy) (mergeUniqueBy (profileRule ^. #uniqueBy) (typeRule ^. #uniqueBy)),+        compiledExternalUriPattern = compileReferenceMatcher mergedReference+      }+  where+    mergedReference = fromMaybe (profileRule ^. #reference) (mergeReferenceRule (profileRule ^. #reference) (typeRule ^. #reference))++-- | Normalize a declared condition for storage in a 'PresenceClause': the shape+-- is unchanged, but the accepted-value list is deduplicated so that a clause+-- reported in a 'ProfileViolation' does not repeat a value the author wrote+-- twice.+compileCondition :: FieldCondition -> FieldCondition+compileCondition rawCondition =+  FieldCondition+    { field = rawCondition ^. #field,+      hasValue = deduplicate (rawCondition ^. #hasValue)+    }++compileReferenceRule :: HandleReferenceRule -> HandleReferenceRule+compileReferenceRule policy =+  HandleReferenceRule+    { localPrefix = policy ^. #localPrefix,+      externalUriSchemes = map Text.toCaseFold (deduplicateSchemes (policy ^. #externalUriSchemes)),+      allowSelf = policy ^. #allowSelf,+      allowLocal = policy ^. #allowLocal,+      externalUriPattern = policy ^. #externalUriPattern+    }++compileExternalUriPattern :: Text -> Either Text Regex+compileExternalUriPattern patternText =+  first Text.pack (Regex.Text.compile defaultCompOpt defaultExecOpt patternText)++compileReferenceMatcher :: Maybe HandleReferenceRule -> Maybe Regex+compileReferenceMatcher policy = do+  patternText <- policy >>= (^. #externalUriPattern)+  either (const Nothing) Just (compileExternalUriPattern patternText)++matchesWholeExternalUriPattern :: Regex -> Text -> Bool+matchesWholeExternalUriPattern regex value =+  case Regex.Text.regexec regex value of+    Right (Just (before, _matched, after, _groups)) -> Text.null before && Text.null after+    _ -> False++compilePathRule :: PathReferenceRule -> PathReferenceRule+compilePathRule policy =+  PathReferenceRule+    { externalUriSchemes = map Text.toCaseFold (deduplicateSchemes (policy ^. #externalUriSchemes)),+      allowSelf = policy ^. #allowSelf+    }++-- | Combine a profile-scope path policy with a type-scope one: intersect the+-- permitted schemes and require both scopes to allow self-reference.+--+-- Unlike 'mergeReferenceRule' this is total and needs no @Maybe@-of-@Maybe@+-- result, because a path policy has no @localPrefix@ — the one thing two+-- handle policies can flatly disagree about. Narrowing to the intersection is+-- the same direction 'mergeVocabulary' takes: a type rule tightens the+-- profile-wide rule and never loosens it.+mergePathRule :: Maybe PathReferenceRule -> Maybe PathReferenceRule -> Maybe PathReferenceRule+mergePathRule Nothing typePolicy = typePolicy+mergePathRule profilePolicy Nothing = profilePolicy+mergePathRule (Just profilePolicy) (Just typePolicy) =+  Just+    PathReferenceRule+      { externalUriSchemes =+          filter+            (`Set.member` Set.fromList (typePolicy ^. #externalUriSchemes))+            (profilePolicy ^. #externalUriSchemes),+        allowSelf = profilePolicy ^. #allowSelf && typePolicy ^. #allowSelf+      }++-- | Either scope may close a shape; an absent declaration is the identity.+mergeClosure :: Maybe Bool -> Maybe Bool -> Maybe Bool+mergeClosure Nothing policy = policy+mergeClosure policy Nothing = policy+mergeClosure (Just left) (Just right) = Just (left && right)++-- | Merge the member maps for a shape across profile and type scopes.+mergeNestedRuleMaps :: Maybe (Map Text EffectiveFieldRule) -> Maybe (Map Text EffectiveFieldRule) -> Maybe (Map Text EffectiveFieldRule)+mergeNestedRuleMaps Nothing typeRules = typeRules+mergeNestedRuleMaps profileRules Nothing = profileRules+mergeNestedRuleMaps (Just profileRules) (Just typeRules) = Just (Map.unionWith mergeEffectiveFieldRule profileRules typeRules)++mergeReferenceRule :: Maybe HandleReferenceRule -> Maybe HandleReferenceRule -> Maybe (Maybe HandleReferenceRule)+mergeReferenceRule Nothing typePolicy = Just typePolicy+mergeReferenceRule profilePolicy Nothing = Just profilePolicy+mergeReferenceRule (Just profilePolicy) (Just typePolicy)+  | profilePolicy ^. #localPrefix == typePolicy ^. #localPrefix,+    Just mergedPattern <- mergeOptionalText (profilePolicy ^. #externalUriPattern) (typePolicy ^. #externalUriPattern) =+      Just . Just $+        HandleReferenceRule+          { localPrefix = profilePolicy ^. #localPrefix,+            externalUriSchemes =+              filter+                (`Set.member` Set.fromList (typePolicy ^. #externalUriSchemes))+                (profilePolicy ^. #externalUriSchemes),+            allowSelf = profilePolicy ^. #allowSelf && typePolicy ^. #allowSelf,+            allowLocal = profilePolicy ^. #allowLocal && typePolicy ^. #allowLocal,+            externalUriPattern = mergedPattern+          }+  | otherwise = Nothing++mergeUniqueBy :: Maybe Text -> Maybe Text -> Maybe (Maybe Text)+mergeUniqueBy = mergeOptionalText++mergeOptionalText :: Maybe Text -> Maybe Text -> Maybe (Maybe Text)+mergeOptionalText Nothing typeValue = Just typeValue+mergeOptionalText profileValue Nothing = Just profileValue+mergeOptionalText profileValue typeValue+  | profileValue == typeValue = Just profileValue+  | otherwise = Nothing++mergeFieldFormat :: Maybe FieldFormat -> Maybe FieldFormat -> Maybe (Maybe FieldFormat)+mergeFieldFormat Nothing typeFormat = Just typeFormat+mergeFieldFormat profileFormat Nothing = Just profileFormat+mergeFieldFormat (Just Uri) (Just typeFormat@(UriWithScheme _)) = Just (Just typeFormat)+mergeFieldFormat (Just profileFormat@(UriWithScheme _)) (Just Uri) = Just (Just profileFormat)+mergeFieldFormat (Just Actor) (Just HumanActor) = Just (Just HumanActor)+mergeFieldFormat (Just HumanActor) (Just Actor) = Just (Just HumanActor)+mergeFieldFormat (Just Integer) (Just NonNegativeInteger) = Just (Just NonNegativeInteger)+mergeFieldFormat (Just NonNegativeInteger) (Just Integer) = Just (Just NonNegativeInteger)+mergeFieldFormat profileFormat typeFormat+  | profileFormat == typeFormat = Just profileFormat+  | otherwise = Nothing++invalidFormatParameter :: FieldFormat -> Maybe (FieldFormat, Text)+invalidFormatParameter fieldFormat =+  case fieldFormat of+    UriWithScheme scheme+      | not (validUriScheme scheme) -> Just (fieldFormat, scheme)+    DocumentHandle prefix+      | not (validDocumentHandlePrefix prefix) -> Just (fieldFormat, prefix)+    _ -> Nothing++validUriScheme :: Text -> Bool+validUriScheme scheme =+  case Text.uncons scheme of+    Just (firstCharacter, rest) -> isAsciiLetter firstCharacter && Text.all validRest rest+    Nothing -> False+  where+    validRest character =+      isAsciiLetter character+        || ('0' <= character && character <= '9')+        || character `elem` ['+', '.', '-']++validDocumentHandlePrefix :: Text -> Bool+validDocumentHandlePrefix prefix =+  case parseDocumentId (prefix <> "-1") of+    Just documentId -> documentId ^. #prefix == prefix+    Nothing -> False++isAsciiLetter :: Char -> Bool+isAsciiLetter character = isAsciiLower character || isAsciiUpper character++mergeCardinality :: Cardinality -> Cardinality -> Cardinality+mergeCardinality Any typeCardinality = typeCardinality+mergeCardinality profileCardinality Any = profileCardinality+mergeCardinality profileCardinality _typeCardinality = profileCardinality++mergeVocabulary :: [Text] -> [Text] -> [Text]+mergeVocabulary [] typeValues = typeValues+mergeVocabulary profileValues [] = profileValues+mergeVocabulary profileValues typeValues =+  filter (`Set.member` Set.fromList typeValues) profileValues++deduplicate :: [Text] -> [Text]+deduplicate = go Set.empty+  where+    go _ [] = []+    go seen (value : rest)+      | value `Set.member` seen = go seen rest+      | otherwise = value : go (Set.insert value seen) rest++deduplicateSchemes :: [Text] -> [Text]+deduplicateSchemes = go Set.empty+  where+    go _ [] = []+    go seen (scheme : rest)+      | normalized `Set.member` seen = go seen rest+      | otherwise = scheme : go (Set.insert normalized seen) rest+      where+        normalized = Text.toCaseFold scheme++effectiveRulesForType :: CompiledProfile -> Text -> Map Text EffectiveFieldRule+effectiveRulesForType compiled ctype =+  Map.findWithDefault (compiled ^. #baseRules) ctype (compiled ^. #rulesByType)++profileFieldDescriptionForType :: CompiledProfile -> Text -> Text -> Maybe Text+profileFieldDescriptionForType compiled ctype key =+  Map.lookup key (effectiveRulesForType compiled ctype) >>= (^. #description)++-- | A parsed document handle: an ASCII-letter-led alphanumeric prefix and a+-- positive number, rendered as @PREFIX-N@.+data DocumentId = DocumentId+  { prefix :: !Text,+    number :: !Natural+  }+  deriving stock (Generic, Eq, Ord, Show)++-- | Parse a strict document handle. The prefix contains one or more ASCII+-- letters or digits and begins with a letter. It is followed by exactly one+-- hyphen and a positive decimal number with no leading zero. Thus @ADR-7@+-- parses, while @ADR-007@, @ADR-0@, @ADR-@, @-7@, @adr 7@, and+-- @ADR-7-extra@ do not.+parseDocumentId :: Text -> Maybe DocumentId+parseDocumentId raw =+  case Text.splitOn "-" raw of+    [prefixText, numberText]+      | validPrefix prefixText,+        validNumberText numberText ->+          case Text.Read.decimal numberText of+            Right (parsedNumber, remainder)+              | Text.null remainder,+                parsedNumber > 0 ->+                  Just (DocumentId prefixText parsedNumber)+            _ -> Nothing+    _ -> Nothing+  where+    validPrefix value =+      case Text.uncons value of+        Just (firstCharacter, rest) ->+          isAsciiLetter firstCharacter && Text.all isAsciiAlphaNumeric rest+        Nothing -> False+    validNumberText value =+      case Text.uncons value of+        Just (firstCharacter, rest) ->+          firstCharacter >= '1'+            && firstCharacter <= '9'+            && Text.all isAsciiDigit rest+        Nothing -> False+    isAsciiDigit character =+      character >= '0' && character <= '9'+    isAsciiAlphaNumeric character =+      isAsciiLetter character || isAsciiDigit character++-- | Render a document handle as @PREFIX-N@.+renderDocumentId :: DocumentId -> Text+renderDocumentId DocumentId {prefix, number} =+  prefix <> "-" <> Text.pack (show number)++-- | Every well-formed handle under the profile's ID field, paired with the+-- concept carrying it and sorted by prefix, number, then concept ID. Concepts+-- without a well-formed handle are omitted. A profile with no ID field yields+-- an empty list.+documentIdsInBundle :: ProfileSpec -> [Concept] -> [(DocumentId, ConceptId)]+documentIdsInBundle spec concepts =+  case spec ^. #idField of+    Nothing -> []+    Just fieldName ->+      List.sortOn+        (\(documentId, cid) -> (documentId, renderConceptId cid))+        [ (documentId, conceptIdOf concept)+        | concept <- concepts,+          Just (String rawDocumentId) <- [frontmatterLookup fieldName (conceptFrontmatter concept)],+          Just documentId <- [parseDocumentId rawDocumentId]+        ]++-- | Allocate one more than the highest document-ID number already used for the+-- given prefix, or number 1 when the prefix is unused. Gaps are deliberately+-- not filled: reusing a retired number could make an old reference silently+-- point at a different document.+nextDocumentId :: ProfileSpec -> [Concept] -> Text -> DocumentId+nextDocumentId spec concepts requestedPrefix =+  DocumentId+    { prefix = requestedPrefix,+      number = highestNumber + 1+    }+  where+    highestNumber =+      List.foldl'+        max+        0+        [ documentId ^. #number+        | (documentId, _) <- documentIdsInBundle spec concepts,+          documentId ^. #prefix == requestedPrefix+        ]++-- | One structural segment of a frontmatter path. EP-2 produces top-level+-- 'FieldName' paths; later bounded nested validation can append field names and+-- array indexes without encoding paths as ad hoc text.+data FieldPathSegment+  = FieldName Text+  | ArrayIndex Int+  deriving stock (Generic, Eq, Ord, Show)++newtype FieldPath = FieldPath+  { segments :: NonEmpty FieldPathSegment+  }+  deriving stock (Generic, Eq, Ord, Show)++topLevelFieldPath :: Text -> FieldPath+topLevelFieldPath key = FieldPath (FieldName key :| [])++nestedDefinitionPath :: Text -> Text -> FieldPath+nestedDefinitionPath parent child =+  FieldPath (FieldName parent :| [FieldName child])++nestedValuePath :: Text -> Int -> Text -> FieldPath+nestedValuePath parent elementIndex child =+  FieldPath (FieldName parent :| [ArrayIndex elementIndex, FieldName child])++nestedElementPath :: Text -> Int -> FieldPath+nestedElementPath parent elementIndex =+  FieldPath (FieldName parent :| [ArrayIndex elementIndex])++-- | A single deviation from a profile. Advisory by default at the CLI layer.+data ProfileViolation+  = -- | concept's @type@ is not listed in the profile and unknown types are disallowed+    ConstraintPresenceMissing ConceptId FieldPath (Maybe FieldCondition)+  | ConstraintAlternativeMissing ConceptId [FieldPath] (Maybe FieldCondition)+  | TimestampOrderViolation ConceptId FieldPath FieldPath+  | TextOperandMismatch ConceptId FieldPath Value+  | MembershipValueMissing ConceptId FieldPath Text ValueSelector+  | DuplicateSelectedValue ConceptId FieldPath Text FieldPath+  | TypeNotInProfile ConceptId Text+  | -- | a required frontmatter key is missing or empty (concept, key, activating condition)+    MissingProfileField ConceptId Text (Maybe FieldCondition)+  | -- | a recommended frontmatter key is missing under strict authoring+    MissingRecommendedProfileField ConceptId Text (Maybe FieldCondition)+  | -- | a required field is missing inside one list element record+    MissingNestedProfileField ConceptId FieldPath (Maybe FieldCondition)+  | -- | a recommended nested field is missing under strict authoring+    MissingRecommendedNestedProfileField ConceptId FieldPath (Maybe FieldCondition)+  | -- | a present value is outside the effective textual vocabulary+    ValueNotInVocabulary ConceptId FieldPath [Text] Value+  | -- | a present value has the wrong scalar/list shape+    CardinalityMismatch ConceptId FieldPath Cardinality Value+  | -- | a present value does not satisfy its named textual format+    ValueFormatMismatch ConceptId FieldPath FieldFormat Value+  | -- | a local reference has the right prefix but no valid owner in this bundle+    DanglingHandleReference ConceptId FieldPath Text+  | -- | a parsed local handle uses a prefix other than the declared target prefix+    ReferenceHandlePrefixMismatch ConceptId FieldPath Text Text+  | -- | a reference value is neither textual local handle nor valid absolute URI+    MalformedDocumentReference ConceptId FieldPath Value+  | -- | an absolute external URI uses a scheme the profile did not permit+    ExternalReferenceSchemeNotAllowed ConceptId FieldPath Text [Text]+  | -- | a syntactically valid local handle is prohibited at this field+    LocalDocumentReferenceNotAllowed ConceptId FieldPath Text+  | -- | an allowed external URI does not match the declared whole-value pattern+    ExternalReferencePatternMismatch ConceptId FieldPath Text Text+  | -- | a local handle, or a bundle path, resolves to the concept carrying it+    SelfDocumentReference ConceptId FieldPath Text+  | -- | a path-valued field's value is not one of the three shapes of §6.2+    MalformedPathReference ConceptId FieldPath Value+  | -- | a relative path climbs above the bundle root+    PathEscapesBundle ConceptId FieldPath Text+  | -- | a bundle path names a concept that does not exist in this bundle+    DanglingPathReference ConceptId FieldPath Text+  | -- | a closed profile does not declare this top-level field+    FieldNotInProfile ConceptId Text+  | -- | a closed nested shape does not declare this member+    NestedFieldNotInProfile ConceptId FieldPath+  | -- | a declared list element is not an object record+    NestedElementNotRecord ConceptId FieldPath Value+  | -- | one valid scalar member value occurs in more than one list element+    DuplicateNestedFieldValue ConceptId FieldPath Value (NonEmpty Int)+  | -- | concept's file path does not match the type rule's pattern (concept, type, pattern)+    PathPatternMismatch ConceptId Text Text+  | -- | type rule requires a resource scheme but resource is absent (concept, type, scheme)+    MissingResource ConceptId Text Text+  | -- | resource present but its scheme is wrong (concept, expected scheme, actual resource)+    ResourceSchemeMismatch ConceptId Text Text+  | -- | required @# Schema@ section is absent (concept, type)+    MissingSchemaSection ConceptId Text+  | -- | @# Schema@ table columns do not match (concept, type, expected, actual)+    SchemaColumnsMismatch ConceptId Text [Text] [Text]+  | -- | type rule declares an @idPrefix@ but the concept has no handle (concept, type, prefix)+    MissingDocumentId ConceptId Text Text+  | -- | handle present but malformed for the declared prefix (concept, prefix, actual value)+    MalformedDocumentId ConceptId Text Text+  | -- | the same handle appears on more than one concept (handle, concept, other concept)+    DuplicateDocumentId Text ConceptId ConceptId+  | -- | the profile requires the bundle to declare an OKF version it does not+    -- (required version, what the bundle declared, 'Nothing' when undeclared)+    --+    -- The only violation that belongs to the bundle rather than to a concept, so+    -- a consumer grouping violations by 'ConceptId' has nothing to key it on.+    RequiredBundleVersionUnmet Text (Maybe Text)+  deriving stock (Generic, Eq, Show)++-- | Check every concept against a compiled profile, returning all deviations.+-- Profile-wide rules apply even to unknown types; a matching type rule adds its+-- frontmatter rules and the existing type-specific structural checks.+--+-- Existence is decided against the concepts themselves, so a @path@ rule can+-- tell whether a target names a concept and cannot tell whether it names+-- @references\/attesters\/revenue.py@; such a target is accepted unchecked.+-- Callers holding a real directory should use 'validateProfileWith'.+validateProfile :: ValidationProfile -> CompiledProfile -> [Concept] -> [ProfileViolation]+validateProfile =+  validateProfileWithPresence conceptsOnly bundleInventoryOfConcepts+  where+    -- Narrowed to @.md@ on purpose. A caller with concepts and no directory can+    -- decide a @.md@ target, because a 'Concept' /is/ a non-reserved @.md@+    -- file — but it has never been able to see §6.3's+    -- @references/attesters/revenue.py@, and answering 'TargetAbsent' for it+    -- would turn a question okf cannot ask into a rejection.+    conceptsOnly conceptInventory resolved+      | FilePath.takeExtension resolved /= ".md" = TargetUnknown+      | bundleInventoryMember resolved conceptInventory = TargetPresent+      | otherwise = TargetAbsent++-- | 'validateProfile' with the bundle's full file inventory, so a @path@ rule+-- can decide whether a target that is not a concept exists.+--+-- Specification §6.3's own example of a path target is+-- @references\/attesters\/revenue.py@, which is not a concept and which+-- 'validateProfile' therefore accepts unchecked. A caller that walked a real+-- directory has 'Okf.Bundle.walkBundleInventory' and can do better. See+-- @docs\/adr\/13-the-references-convention-and-non-markdown-files.md@.+--+-- Passing an inventory does not make validation touch the filesystem. The+-- inventory is data read once during the bundle walk, where okf is already doing+-- IO, which is the shape @docs\/adr\/5-compile-profile-rules-before-validation.md@+-- requires and the one the core §6.2 check already uses.+validateProfileWith :: BundleInventory -> ValidationProfile -> CompiledProfile -> [Concept] -> [ProfileViolation]+validateProfileWith inventory =+  validateProfileWithPresence everyFile (const inventory)+  where+    everyFile fullInventory resolved+      | bundleInventoryMember resolved fullInventory = TargetPresent+      | otherwise = TargetAbsent++-- | Check a bundle's specification §12 version declaration against the profile's+-- @requireBundleVersion@ setting. Returns @[]@ when the profile requires nothing,+-- which is the default and the case for almost every profile.+--+-- Deliberately a separate entry point rather than a parameter on+-- 'validateProfile' and 'validateProfileWith'. Those two are public and their+-- signatures are depended on downstream, and this check consults no concepts at+-- all: threading a bundle-scoped question through a concept-walking function+-- would be misleading as well as breaking.+--+-- §12 makes the declaration a MAY, so okf's own validator never asks for one —+-- see @docs\/adr\/10-okf-version-declaration-and-best-effort-reading.md@. This is+-- the house-convention half: nothing is reported unless a profile author wrote+-- the field.+--+-- A declaration okf cannot parse counts as unmet. It cannot be compared, okf+-- already reports it separately as a strict-mode authoring lint, and silently+-- passing it would let a typo satisfy a requirement.+validateProfileVersion :: VersionDeclaration -> CompiledProfile -> [ProfileViolation]+validateProfileVersion declaration compiled =+  case compiledProfileRequiredBundleVersion compiled of+    Nothing -> []+    Just required ->+      let unmet = [RequiredBundleVersionUnmet (renderOkfVersion required) declaredText]+       in case declaration of+            -- A bundle ahead of the house minimum is not a deviation: §12 defines+            -- a minor bump as backward-compatible additions.+            VersionDeclared declared | declared >= required -> []+            VersionDeclared _ -> unmet+            VersionUnparseable _ -> unmet+            VersionUndeclared -> unmet+  where+    declaredText = case declaration of+      VersionDeclared declared -> Just (renderOkfVersion declared)+      VersionUnparseable rawVersion -> Just rawVersion+      VersionUndeclared -> Nothing++-- | The shared body of 'validateProfile' and 'validateProfileWith'.+--+-- The first argument decides what a @path@ rule may conclude about a resolved+-- §6.2 target; the second supplies the inventory it consults, derived from the+-- concepts when the caller has no directory to walk. Keeping one implementation+-- is what stops the two entry points from drifting apart on everything /except/+-- the one question that distinguishes them.+validateProfileWithPresence ::+  (BundleInventory -> FilePath -> PathTargetPresence) ->+  ([Concept] -> BundleInventory) ->+  ValidationProfile ->+  CompiledProfile ->+  [Concept] ->+  [ProfileViolation]+validateProfileWithPresence presenceRule inventoryOf validationProfile compiled concepts =+  concatMap checkConcept sortedConcepts <> checkDuplicateDocumentIds spec sortedConcepts+  where+    spec = compiledProfileSpec compiled+    sortedConcepts = List.sortOn (renderConceptId . conceptIdOf) concepts+    rulesByType = [(rule ^. #type_, rule) | rule <- spec ^. #types]+    validDocumentIdIndex = buildValidDocumentIdIndex spec rulesByType sortedConcepts+    -- What this caller can say about a resolved §6.2 path, built once.+    presenceOf = presenceRule (inventoryOf sortedConcepts)++    checkConcept concept =+      let cid = conceptIdOf concept+          ctype = conceptType concept+          fieldViolations = checkFields cid ctype concept <> checkUnknownFields cid ctype concept+       in case lookup ctype rulesByType of+            Nothing ->+              [TypeNotInProfile cid ctype | not (spec ^. #allowUnknownTypes)] <> fieldViolations+            Just rule ->+              fieldViolations+                <> checkPath cid ctype rule+                <> checkResource cid ctype rule concept+                <> checkSchema cid ctype rule concept+                <> checkDocumentId spec cid ctype rule concept++    checkFields cid ctype concept =+      List.nub $+        concatMap checkField (Map.toAscList (effectiveRulesForType compiled ctype))+          <> validateConceptConstraints cid topLevelFieldPath (\k -> frontmatterLookup k (conceptFrontmatter concept)) (effectiveRulesForType compiled ctype) (compiledProfileConstraintsForType compiled ctype)+      where+        checkField (key, rule) =+          case evaluateFieldValue rule (frontmatterLookup key (conceptFrontmatter concept)) of+            FieldAbsent actual ->+              presenceViolations key rule+                <> maybe [] (vocabularyViolations key rule) actual+                <> maybe [] (formatViolations key rule) actual+                <> maybe [] (referenceViolations (topLevelFieldPath key) rule) actual+                <> maybe [] (pathViolations (topLevelFieldPath key) rule) actual+            FieldPresent actual ->+              vocabularyViolations key rule actual+                <> formatViolations key rule actual+                <> referenceViolations (topLevelFieldPath key) rule actual+                <> pathViolations (topLevelFieldPath key) rule actual+                <> nestedViolations key rule actual+                <> objectViolations key rule actual+            FieldWrongShape actual -> [CardinalityMismatch cid (topLevelFieldPath key) (rule ^. #cardinality) actual]++        presenceViolations key rule =+          case applicablePresenceClause validationProfile (\sourceKey -> frontmatterLookup sourceKey (conceptFrontmatter concept)) rule of+            Nothing -> []+            Just clause ->+              [ case clause ^. #requirement of+                  RequiredField -> MissingProfileField cid key (clause ^. #condition)+                  RecommendedField -> MissingRecommendedProfileField cid key (clause ^. #condition)+              ]+        vocabularyViolations key rule actual =+          [ ValueNotInVocabulary cid (topLevelFieldPath key) (rule ^. #allowedValues) actual+          | not (null (rule ^. #allowedValues)),+            not (valueMatchesVocabulary (rule ^. #allowedValues) actual)+          ]+        formatViolations key rule actual =+          [ ValueFormatMismatch cid (topLevelFieldPath key) fieldFormat actual+          | Just fieldFormat <- [rule ^. #format],+            not (valueMatchesFormat fieldFormat actual)+          ]+        referenceViolations fieldPath rule actual =+          case rule ^. #reference of+            Nothing -> []+            Just policy -> validateReferenceValue validDocumentIdIndex cid fieldPath policy (rule ^. #compiledExternalUriPattern) actual++        -- Takes a 'FieldPath' rather than a key because it is shared by all+        -- three scopes: a top-level key, a member of a list element, and a+        -- member of an object-valued mapping.+        pathViolations fieldPath rule actual =+          case rule ^. #path of+            Nothing -> []+            Just policy -> validatePathValue presenceOf cid fieldPath policy actual++        nestedViolations parentKey parentRule = \case+          Array elementValues+            | Just nestedRules <- parentRule ^. #elementFields ->+                let indexedElements = zip [0 ..] (Vector.toList elementValues)+                 in concat+                      [ case elementValue of+                          Aeson.Object members ->+                            unknownRecordMembers (nestedValuePath parentKey elementIndex) nestedRules (parentRule ^. #elementAllowsUnknownFields) members+                              <> concatMap+                                (checkRecordMember (nestedValuePath parentKey elementIndex) members)+                                (Map.toAscList nestedRules)+                              <> validateConceptConstraints cid (nestedValuePath parentKey elementIndex) (\k -> Aeson.KeyMap.lookup (Aeson.Key.fromText k) members) nestedRules (parentRule ^. #elementConstraints)+                          _ -> [NestedElementNotRecord cid (nestedElementPath parentKey elementIndex) elementValue]+                      | (elementIndex, elementValue) <- indexedElements+                      ]+                      <> uniquenessViolations parentKey parentRule nestedRules indexedElements+          _ -> []++        -- The mapping spelling of the same idea. The value /is/ the record, so+        -- there is no index in the path: a member is reported as+        -- @generated.by@ rather than @generated[0].by@.+        objectViolations parentKey parentRule = \case+          Aeson.Object members+            | Just objectRules <- parentRule ^. #objectFields ->+                unknownRecordMembers (nestedDefinitionPath parentKey) objectRules (parentRule ^. #objectAllowsUnknownFields) members+                  <> concatMap+                    (checkRecordMember (nestedDefinitionPath parentKey) members)+                    (Map.toAscList objectRules)+                  <> validateConceptConstraints cid (nestedDefinitionPath parentKey) (\k -> Aeson.KeyMap.lookup (Aeson.Key.fromText k) members) objectRules (parentRule ^. #objectConstraints)+          _ -> []++        unknownRecordMembers buildPath rules policy members =+          [ NestedFieldNotInProfile cid (buildPath key)+          | policy == Just False,+            key <- List.sort (map Aeson.Key.toText (Aeson.KeyMap.keys members)),+            Map.notMember key rules+          ]++        -- Check one member of one record. Shared by the list-element and+        -- object-value walks, which differ only in how they name the member;+        -- the sibling lookup that resolves a @when@ condition stays scoped to+        -- the record the member lives in either way.+        checkRecordMember buildPath members (key, rule) =+          let path = buildPath key+              actualValue = Aeson.KeyMap.lookup (Aeson.Key.fromText key) members+           in case evaluateFieldValue rule actualValue of+                FieldAbsent actual ->+                  nestedPresenceViolations members path rule+                    <> maybe [] (nestedVocabularyViolations path rule) actual+                    <> maybe [] (nestedFormatViolations path rule) actual+                    <> maybe [] (referenceViolations path rule) actual+                    <> maybe [] (pathViolations path rule) actual+                FieldPresent actual ->+                  nestedVocabularyViolations path rule actual+                    <> nestedFormatViolations path rule actual+                    <> referenceViolations path rule actual+                    <> pathViolations path rule actual+                FieldWrongShape actual -> [CardinalityMismatch cid path (rule ^. #cardinality) actual]++        nestedPresenceViolations objectFields path rule =+          case applicablePresenceClause validationProfile lookupSibling rule of+            Nothing -> []+            Just clause ->+              [ case clause ^. #requirement of+                  RequiredField -> MissingNestedProfileField cid path (clause ^. #condition)+                  RecommendedField -> MissingRecommendedNestedProfileField cid path (clause ^. #condition)+              ]+          where+            lookupSibling sourceKey = Aeson.KeyMap.lookup (Aeson.Key.fromText sourceKey) objectFields+        nestedVocabularyViolations path rule actual =+          [ ValueNotInVocabulary cid path (rule ^. #allowedValues) actual+          | not (null (rule ^. #allowedValues)),+            not (valueMatchesVocabulary (rule ^. #allowedValues) actual)+          ]+        nestedFormatViolations path rule actual =+          [ ValueFormatMismatch cid path fieldFormat actual+          | Just fieldFormat <- [rule ^. #format],+            not (valueMatchesFormat fieldFormat actual)+          ]++        uniquenessViolations parentKey parentRule nestedRules indexedElements =+          case parentRule ^. #uniqueBy of+            Nothing -> []+            Just key ->+              case Map.lookup key nestedRules of+                Nothing -> []+                Just keyRule ->+                  [ DuplicateNestedFieldValue cid (nestedDefinitionPath parentKey key) duplicateValue (firstIndex :| remainingIndices)+                  | (duplicateValue, firstIndex : remainingIndices) <- groupedValues key keyRule indexedElements,+                    not (null remainingIndices)+                  ]++        groupedValues key keyRule =+          List.foldl' insertValue [] . mapMaybe participant+          where+            participant (elementIndex, Aeson.Object members) =+              case evaluateFieldValue keyRule (Aeson.KeyMap.lookup (Aeson.Key.fromText key) members) of+                FieldPresent scalarValue -> Just (scalarValue, elementIndex)+                _ -> Nothing+            participant _ = Nothing++            insertValue [] (value, elementIndex) = [(value, [elementIndex])]+            insertValue ((groupValue, elementIndices) : remaining) (value, elementIndex)+              | groupValue == value = (groupValue, elementIndices <> [elementIndex]) : remaining+              | otherwise = (groupValue, elementIndices) : insertValue remaining (value, elementIndex)++    checkUnknownFields cid ctype concept+      | spec ^. #allowUnknownFields = []+      | otherwise =+          [ FieldNotInProfile cid key+          | key <- frontmatterKeys (conceptFrontmatter concept),+            key `Set.notMember` allowedFields ctype+          ]++    allowedFields ctype =+      coreFrontmatterFields+        <> Map.keysSet (effectiveRulesForType compiled ctype)+        <> maybe Set.empty Set.singleton (spec ^. #idField)++-- | Index only handles that are valid owners under the compiled profile's raw+-- type declarations: the concept has a matching type rule, that rule declares+-- the parsed handle's exact prefix, and the profile declares the owning field.+-- Multiple owners are retained so a duplicate target still counts as existing;+-- the existing bundle-wide duplicate diagnostic remains authoritative.+buildValidDocumentIdIndex :: ProfileSpec -> [(Text, TypeRule)] -> [Concept] -> Map DocumentId [ConceptId]+buildValidDocumentIdIndex spec rulesByType concepts =+  case spec ^. #idField of+    Nothing -> Map.empty+    Just fieldName ->+      Map.fromListWith+        (flip (<>))+        [ (documentId, [conceptIdOf concept])+        | concept <- concepts,+          Just typeRule <- [lookup (conceptType concept) rulesByType],+          Just expectedPrefix <- [typeRule ^. #idPrefix],+          Just (String rawDocumentId) <- [frontmatterLookup fieldName (conceptFrontmatter concept)],+          Just documentId <- [parseDocumentId rawDocumentId],+          documentId ^. #prefix == expectedPrefix+        ]++validateReferenceValue :: Map DocumentId [ConceptId] -> ConceptId -> FieldPath -> HandleReferenceRule -> Maybe Regex -> Value -> [ProfileViolation]+validateReferenceValue validOwners sourceConcept path policy matcher = \case+  String rawReference -> validateReferenceText validOwners sourceConcept path policy matcher rawReference+  Array values ->+    concat+      [ case value of+          String rawReference -> validateReferenceText validOwners sourceConcept (appendArrayIndex path elementIndex) policy matcher rawReference+          _ -> [MalformedDocumentReference sourceConcept (appendArrayIndex path elementIndex) value]+      | (elementIndex, value) <- zip [0 ..] (Vector.toList values)+      ]+  actual -> [MalformedDocumentReference sourceConcept path actual]++validateReferenceText :: Map DocumentId [ConceptId] -> ConceptId -> FieldPath -> HandleReferenceRule -> Maybe Regex -> Text -> [ProfileViolation]+validateReferenceText validOwners sourceConcept path policy matcher rawReference =+  case parseDocumentId rawReference of+    Just documentId+      | not (policy ^. #allowLocal) ->+          [LocalDocumentReferenceNotAllowed sourceConcept path rawReference]+      | documentId ^. #prefix /= policy ^. #localPrefix ->+          [ReferenceHandlePrefixMismatch sourceConcept path rawReference (policy ^. #localPrefix)]+      | otherwise ->+          case Map.lookup documentId validOwners of+            Nothing -> [DanglingHandleReference sourceConcept path rawReference]+            Just owners+              | not (policy ^. #allowSelf),+                sourceConcept `elem` owners ->+                  [SelfDocumentReference sourceConcept path rawReference]+              | otherwise -> []+    Nothing ->+      case parseURI (Text.unpack rawReference) of+        Just parsed+          | not (Text.null normalizedScheme),+            normalizedScheme `elem` policy ^. #externalUriSchemes ->+              case (policy ^. #externalUriPattern, matcher) of+                (Nothing, _) -> []+                (Just patternText, Just compiledPattern)+                  | matchesWholeExternalUriPattern compiledPattern rawReference -> []+                  | otherwise -> [ExternalReferencePatternMismatch sourceConcept path rawReference patternText]+                (Just patternText, Nothing) -> [ExternalReferencePatternMismatch sourceConcept path rawReference patternText]+          | not (Text.null normalizedScheme) ->+              [ ExternalReferenceSchemeNotAllowed+                  sourceConcept+                  path+                  normalizedScheme+                  (policy ^. #externalUriSchemes)+              ]+          | otherwise -> [MalformedDocumentReference sourceConcept path (String rawReference)]+          where+            normalizedScheme = Text.toCaseFold (Text.dropWhileEnd (== ':') (Text.pack (uriScheme parsed)))+        Nothing -> [MalformedDocumentReference sourceConcept path (String rawReference)]++-- | Check one path-valued frontmatter value, at any scope. A list is checked+-- element-wise so that a diagnostic names @sources[1].resource@ rather than the+-- whole list.+validatePathValue :: (FilePath -> PathTargetPresence) -> ConceptId -> FieldPath -> PathReferenceRule -> Value -> [ProfileViolation]+validatePathValue presenceOf sourceConcept path policy = \case+  String rawPath -> validatePathText presenceOf sourceConcept path policy rawPath+  Array values ->+    concat+      [ case value of+          String rawPath ->+            validatePathText presenceOf sourceConcept (appendArrayIndex path elementIndex) policy rawPath+          _ -> [MalformedPathReference sourceConcept (appendArrayIndex path elementIndex) value]+      | (elementIndex, value) <- zip [0 ..] (Vector.toList values)+      ]+  actual -> [MalformedPathReference sourceConcept path actual]++-- | What a caller can say about a resolved §6.2 bundle path.+--+-- Three answers rather than two, because "I cannot tell" is a real state and+-- collapsing it into "absent" turns silence into a rejection. 'validateProfile'+-- is handed concepts alone, so it genuinely cannot say whether §6.3's+-- @references\/attesters\/revenue.py@ is there, and reporting it as dangling+-- would be a claim okf did not check.+data PathTargetPresence+  = -- | The bundle holds it.+    TargetPresent+  | -- | The bundle does not hold it, and the caller can see enough to be sure.+    TargetAbsent+  | -- | The caller cannot answer for this path.+    TargetUnknown+  deriving stock (Generic, Eq, Show)++-- | Check one path value against the §6.2 grammar and the profile's policy.+--+-- Every diagnostic carries the raw text the author wrote rather than the+-- collapsed path okf computed from it, so the message names something findable+-- in the file.+--+-- Existence is decided by the supplied lookup, which reports what the caller can+-- actually see: 'validateProfileWith' holds a real directory's inventory and so+-- resolves §6.3's own @references\/attesters\/revenue.py@, while+-- 'validateProfile' holds the concepts alone and answers 'TargetUnknown' for it.+--+-- The @.md@ branch still goes through 'conceptIdFromFilePath', because that is+-- what decides self-reference and what makes 'MalformedPathReference' reachable+-- for a path no concept ID could be built from. What it no longer decides is+-- whether the target is there.+validatePathText :: (FilePath -> PathTargetPresence) -> ConceptId -> FieldPath -> PathReferenceRule -> Text -> [ProfileViolation]+validatePathText presenceOf sourceConcept path policy rawPath =+  case classifyPathReference sourceConcept rawPath of+    ExternalUrl scheme+      | scheme `elem` policy ^. #externalUriSchemes -> []+      | otherwise ->+          [ExternalReferenceSchemeNotAllowed sourceConcept path scheme (policy ^. #externalUriSchemes)]+    EscapesBundle -> [PathEscapesBundle sourceConcept path rawPath]+    MalformedPath -> [MalformedPathReference sourceConcept path (String rawPath)]+    BundlePath resolved+      | FilePath.takeExtension resolved == ".md" ->+          case conceptIdFromFilePath resolved of+            Left _ -> [MalformedPathReference sourceConcept path (String rawPath)]+            Right target+              | target == sourceConcept,+                not (policy ^. #allowSelf) ->+                  [SelfDocumentReference sourceConcept path rawPath]+              | otherwise -> danglingWhenAbsent resolved+      | otherwise -> danglingWhenAbsent resolved+  where+    danglingWhenAbsent resolved = case presenceOf resolved of+      TargetAbsent -> [DanglingPathReference sourceConcept path rawPath]+      TargetPresent -> []+      TargetUnknown -> []++appendArrayIndex :: FieldPath -> Int -> FieldPath+appendArrayIndex (FieldPath pathSegments) elementIndex =+  FieldPath (pathSegments <> (ArrayIndex elementIndex :| []))++applicablePresenceClause :: ValidationProfile -> (Text -> Maybe Value) -> EffectiveFieldRule -> Maybe PresenceClause+applicablePresenceClause validationProfile lookupValue rule =+  List.find applies requiredClauses+    <|> if validationProfile == StrictAuthoring then List.find applies recommendedClauses else Nothing+  where+    requiredClauses = filter ((== RequiredField) . (^. #requirement)) (rule ^. #presenceClauses)+    recommendedClauses = filter ((== RecommendedField) . (^. #requirement)) (rule ^. #presenceClauses)+    applies clause = maybe True conditionApplies (clause ^. #condition)+    conditionApplies condition =+      case lookupValue (condition ^. #field) of+        Just (String actual) -> actual `elem` condition ^. #hasValue+        _ -> False++valueMatchesVocabulary :: [Text] -> Value -> Bool+valueMatchesVocabulary allowed = \case+  String value -> value `elem` allowed+  Array values -> all elementMatches (Vector.toList values)+  _ -> False+  where+    elementMatches (String value) = value `elem` allowed+    elementMatches _ = False++-- | Whether a present value satisfies a format. Each format declares which+-- value shapes it can match at all: the textual formats match a string, the+-- numeric ones a YAML number, and 'Boolean' a YAML boolean. A list is matched+-- by recursing, so a list of integers satisfies an @integer@ format for the+-- same reason a list of timestamps satisfies @rfc3339-utc@ — a format+-- constrains a value, and a list is a list of values.+valueMatchesFormat :: FieldFormat -> Value -> Bool+valueMatchesFormat fieldFormat actual =+  case actual of+    String value -> textMatchesFormat fieldFormat value+    Array values -> all (valueMatchesFormat fieldFormat) (Vector.toList values)+    Number _ -> fieldFormat == FiniteDecimal || numberMatchesFormat fieldFormat actual+    Bool _ -> fieldFormat == Boolean+    _ -> False++textMatchesFormat :: FieldFormat -> Text -> Bool+textMatchesFormat fieldFormat value =+  case fieldFormat of+    Rfc3339Utc ->+      hasExtendedUtcShape value+        && isJust (iso8601ParseM (Text.unpack value) :: Maybe UTCTime)+    Date ->+      hasExtendedDateShape value+        && isJust (iso8601ParseM (Text.unpack value) :: Maybe Day)+    Uri -> isJust (parseURI (Text.unpack value))+    UriWithScheme expectedScheme ->+      case parseURI (Text.unpack value) of+        Just parsed ->+          Text.toCaseFold (Text.dropWhileEnd (== ':') (Text.pack (uriScheme parsed)))+            == Text.toCaseFold expectedScheme+        Nothing -> False+    DocumentHandle expectedPrefix ->+      case parseDocumentId value of+        Just documentId -> documentId ^. #prefix == expectedPrefix+        Nothing -> False+    -- Specification §7 defines exactly three actor shapes, and+    -- 'Actor.parseActor' classifies them, so the format is a case match on its+    -- result rather than a second parser. A value the convention does not+    -- define — the specification's own illustrative @team:ga4-docs@ among them —+    -- is 'Actor.UnclassifiedActor' and is reported.+    Actor ->+      case Actor.parseActor value of+        Actor.UnclassifiedActor _ -> False+        _ -> True+    HumanActor -> Actor.isHumanActor (Actor.parseActor value)+    -- A numeric or boolean format never matches text. A @usage_count: "5000"@+    -- is a quoted string in YAML and is reported rather than coerced, which is+    -- the whole point of being able to declare the format.+    Integer -> False+    NonNegativeInteger -> False+    FiniteDecimal -> False+    Boolean -> False++-- | Whether a YAML number satisfies a numeric format. Uses aeson's own+-- 'Integer' decoder, which already rejects a non-integral number, rather than+-- reaching for @scientific@: that package is a dependency of @aeson@ but not of+-- @okf-core@, so it is importable in a scratch experiment and not from here.+-- 'Okf.Document.objectInteger' takes the same route.+numberMatchesFormat :: FieldFormat -> Value -> Bool+numberMatchesFormat fieldFormat actual =+  case Aeson.fromJSON actual :: Aeson.Result Integer of+    Aeson.Error _ -> False+    Aeson.Success parsed ->+      case fieldFormat of+        Integer -> True+        NonNegativeInteger -> parsed >= 0+        _ -> False++hasExtendedDateShape :: Text -> Bool+hasExtendedDateShape value =+  Text.length value == 10+    && Text.index value 4 == '-'+    && Text.index value 7 == '-'++hasExtendedUtcShape :: Text -> Bool+hasExtendedUtcShape value =+  Text.length value >= 20+    && Text.index value 4 == '-'+    && Text.index value 7 == '-'+    && Text.index value 10 == 'T'+    && Text.index value 13 == ':'+    && Text.index value 16 == ':'+    && Text.last value == 'Z'++data FieldValueEvaluation+  = FieldAbsent (Maybe Value)+  | FieldPresent Value+  | FieldWrongShape Value++-- | Decide whether a frontmatter value counts as present for one rule. Takes the+-- whole rule rather than just its cardinality because the 'Any' case has to know+-- whether the rule declares object members: a rule accepting both spellings of+-- the OKF v0.2 @verified@ key stays at 'Any' cardinality and must still count a+-- mapping as present.+--+-- This is the single point at which okf decides presence, so a change here+-- affects every profile check.+evaluateFieldValue :: EffectiveFieldRule -> Maybe Value -> FieldValueEvaluation+evaluateFieldValue _ Nothing = FieldAbsent Nothing+evaluateFieldValue rule (Just actual) =+  case rule ^. #cardinality of+    Any+      | legacyValueIsPresent actual -> FieldPresent actual+      -- A rule that also accepts a mapping counts a non-empty one as present.+      -- Without this a profile declaring both shapes would report `verified`+      -- missing on a document that writes it as a bare mapping.+      | isJust (rule ^. #objectFields), nonEmptyObject actual -> FieldPresent actual+      | otherwise -> FieldAbsent (Just actual)+    Scalar ->+      case actual of+        String value+          | Text.null (Text.strip value) -> FieldAbsent (Just actual)+          | otherwise -> FieldPresent actual+        Number _ -> FieldPresent actual+        Bool _ -> FieldPresent actual+        _ -> FieldWrongShape actual+    List ->+      case actual of+        Array values+          | null values -> FieldAbsent (Just actual)+          | otherwise -> FieldPresent actual+        _ -> FieldWrongShape actual+    Object+      -- An empty mapping is treated as absent for the same reason an empty list+      -- is: a key written with no content is the author saying nothing, and+      -- reporting it missing is more useful than reporting it present and empty.+      | nonEmptyObject actual -> FieldPresent actual+      | isObject actual -> FieldAbsent (Just actual)+      | otherwise -> FieldWrongShape actual++isObject :: Value -> Bool+isObject = \case+  Aeson.Object _ -> True+  _ -> False++nonEmptyObject :: Value -> Bool+nonEmptyObject = \case+  Aeson.Object members -> not (Aeson.KeyMap.null members)+  _ -> False++legacyValueIsPresent :: Value -> Bool+legacyValueIsPresent = \case+  String value -> not (Text.null (Text.strip value))+  Array values -> not (null values)+  _ -> False++-- | Check a profile-declared document ID for one concept.+checkDocumentId :: ProfileSpec -> ConceptId -> Text -> TypeRule -> Concept -> [ProfileViolation]+checkDocumentId spec cid ctype rule concept =+  case (spec ^. #idField, rule ^. #idPrefix) of+    (Just fieldName, Just expectedPrefix) ->+      case frontmatterLookup fieldName (conceptFrontmatter concept) of+        Just (String value)+          | not (Text.null (Text.strip value)) ->+              case parseDocumentId value of+                Just documentId+                  | documentId ^. #prefix == expectedPrefix -> []+                _ -> [MalformedDocumentId cid expectedPrefix value]+        _ -> [MissingDocumentId cid ctype expectedPrefix]+    _ -> []++-- | Check every non-empty value under the profile's ID field for bundle-wide+-- uniqueness. Concept IDs are sorted before grouping so output is deterministic.+checkDuplicateDocumentIds :: ProfileSpec -> [Concept] -> [ProfileViolation]+checkDuplicateDocumentIds spec concepts =+  case spec ^. #idField of+    Nothing -> []+    Just fieldName ->+      concatMap duplicateViolations (groupedHandles fieldName)+  where+    groupedHandles fieldName =+      List.groupBy+        (\(leftHandle, _) (rightHandle, _) -> leftHandle == rightHandle)+        (handles fieldName)+    handles fieldName =+      List.sortOn+        (\(handle, cid) -> (handle, renderConceptId cid))+        [ (handle, conceptIdOf concept)+        | concept <- concepts,+          Just (String handle) <- [frontmatterLookup fieldName (conceptFrontmatter concept)],+          not (Text.null (Text.strip handle))+        ]+    duplicateViolations ((handle, firstConcept) : duplicates) =+      [ DuplicateDocumentId handle firstConcept duplicateConcept+      | (_, duplicateConcept) <- duplicates+      ]+    duplicateViolations [] = []++-- | Project a concept's frontmatter (the document's @frontmatter@ field).+conceptFrontmatter :: Concept -> Frontmatter+conceptFrontmatter concept = conceptDocument concept ^. #frontmatter++-- | A type rule's @pathPattern@, when present, constrains where the concept's+-- file may live.+checkPath :: ConceptId -> Text -> TypeRule -> [ProfileViolation]+checkPath cid ctype rule =+  case rule ^. #pathPattern of+    Nothing -> []+    Just patternText+      | matchPathPattern patternText cid -> []+      | otherwise -> [PathPatternMismatch cid ctype patternText]++-- | Match a concept ID against a segment-glob pattern. @*@ matches exactly one+-- segment; a single trailing @**@ matches one or more remaining segments; every+-- other segment matches literally. Both segment lists must be consumed exactly,+-- except for the trailing @**@ case.+matchPathPattern :: Text -> ConceptId -> Bool+matchPathPattern patternText cid =+  go (Text.splitOn "/" patternText) (Text.splitOn "/" (renderConceptId cid))+  where+    go [] [] = True+    go ["**"] (_ : _) = True+    go ("*" : ps) (_ : ss) = go ps ss+    go (p : ps) (s : ss) = p == s && go ps ss+    go _ _ = False++-- | A type rule's @resourceScheme@, when present, requires a @resource:@ value+-- whose scheme matches.+checkResource :: ConceptId -> Text -> TypeRule -> Concept -> [ProfileViolation]+checkResource cid ctype rule concept =+  case rule ^. #resourceScheme of+    Nothing -> []+    Just scheme ->+      case conceptResource concept of+        Nothing -> [MissingResource cid ctype scheme]+        Just value+          | (scheme <> "://") `Text.isPrefixOf` value -> []+          | otherwise -> [ResourceSchemeMismatch cid scheme value]++-- | A type rule's @# Schema@ contract: when @requireSchemaSection@ is set, the+-- body must contain a @# Schema@ section whose table header begins with the+-- required @schemaColumns@ (case-insensitive, trimmed, compared as a prefix so a+-- team may add trailing columns without tripping the check).+checkSchema :: ConceptId -> Text -> TypeRule -> Concept -> [ProfileViolation]+checkSchema cid ctype rule concept+  | not (rule ^. #requireSchemaSection) = []+  | otherwise =+      case schemaSectionColumns (conceptDocument concept ^. #body) of+        Nothing -> [MissingSchemaSection cid ctype]+        Just actual ->+          let expected = rule ^. #schemaColumns+              norm = map (Text.toLower . Text.strip)+           in [ SchemaColumnsMismatch cid ctype expected actual+              | not (norm expected `List.isPrefixOf` norm actual)+              ]++-- | The header-row columns of the first GitHub-flavored table that follows the+-- first top-level @# Schema@ heading, or 'Nothing' if there is no Schema heading+-- or no following table. Columns are trimmed.+schemaSectionColumns :: Text -> Maybe [Text]+schemaSectionColumns markdown =+  let CMarkGFM.Node _ _ topLevel = CMarkGFM.commonmarkToNode markdownOptions [CMarkGFM.extTable] markdown+   in firstTableAfterSchema topLevel++firstTableAfterSchema :: [CMarkGFM.Node] -> Maybe [Text]+firstTableAfterSchema topLevel =+  case dropWhile (not . isSchemaHeading) topLevel of+    (_heading : rest) -> headerRow rest+    [] -> Nothing+  where+    isSchemaHeading (CMarkGFM.Node _ (CMarkGFM.HEADING _) inner) =+      Text.toLower (Text.strip (nodeText inner)) == "schema"+    isSchemaHeading _ = False++    headerRow [] = Nothing+    headerRow (CMarkGFM.Node _ (CMarkGFM.TABLE _) tableChildren : _) =+      case tableChildren of+        (CMarkGFM.Node _ CMarkGFM.TABLE_ROW cells : _) -> Just (map cellText cells)+        _ -> Nothing+    headerRow (_ : more) = headerRow more++    cellText (CMarkGFM.Node _ _ inner) = Text.strip (nodeText inner)++-- | Concatenate all @TEXT@/@CODE@ literals under a node list, recursively.+nodeText :: [CMarkGFM.Node] -> Text+nodeText = foldMap go+  where+    go (CMarkGFM.Node _ (CMarkGFM.TEXT t) _) = t+    go (CMarkGFM.Node _ (CMarkGFM.CODE t) _) = t+    go (CMarkGFM.Node _ _ inner) = nodeText inner++containsProductDiscoveryField :: Expr Src Void -> Bool+containsProductDiscoveryField = anyOf (cosmosOf Dhall.Core.subExpressions) $ \case+  Dhall.Core.RecordLit fields ->+    any+      (`Dhall.Map.member` fields)+      ["presenceConstraints", "timestampOrderConstraints", "membershipConstraints", "uniqueValuesConstraints"]+  _ -> False++-- | Bounded locations; operators determine whether to observe the whole value+-- or project textual occurrences from a leaf list.+data ValueSelector = ValueSelector {field :: !Text, member :: !(Maybe Text)}+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall, ToJSON)++data PresenceConstraint = PresenceConstraint+  { when :: !(Maybe FieldCondition),+    whenAnyPresent :: ![ValueSelector],+    requireAll :: ![ValueSelector],+    requireAny :: ![ValueSelector]+  }+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall, ToJSON)++data TimestampOrderConstraint = TimestampOrderConstraint {before :: !Text, after :: !Text}+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall, ToJSON)++data MembershipConstraint = MembershipConstraint {source :: !ValueSelector, target :: !ValueSelector}+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall, ToJSON)++newtype UniqueValuesConstraint = UniqueValuesConstraint {selectors :: [ValueSelector]}+  deriving stock (Generic, Eq, Ord, Show)+  deriving anyclass (FromDhall, ToJSON)++-- | Opaque conjunction of constraints, in declaration order within each kind.+data EffectiveConceptConstraints = EffectiveConceptConstraints+  { presenceConstraints :: ![PresenceConstraint],+    timestampOrderConstraints :: ![TimestampOrderConstraint],+    membershipConstraints :: ![MembershipConstraint],+    uniqueValuesConstraints :: ![UniqueValuesConstraint],+    resolvedSelectors :: !(Map ValueSelector EffectiveFieldRule)+  }+  deriving stock (Generic, Eq, Show)++conceptPresenceConstraints :: EffectiveConceptConstraints -> [PresenceConstraint]+conceptPresenceConstraints c = c ^. #presenceConstraints++conceptTimestampOrderConstraints :: EffectiveConceptConstraints -> [TimestampOrderConstraint]+conceptTimestampOrderConstraints c = c ^. #timestampOrderConstraints++conceptMembershipConstraints :: EffectiveConceptConstraints -> [MembershipConstraint]+conceptMembershipConstraints c = c ^. #membershipConstraints++conceptUniqueValuesConstraints :: EffectiveConceptConstraints -> [UniqueValuesConstraint]+conceptUniqueValuesConstraints c = c ^. #uniqueValuesConstraints++emptyConstraints :: EffectiveConceptConstraints+emptyConstraints = EffectiveConceptConstraints [] [] [] [] Map.empty++frontmatterConstraints :: FrontmatterRules -> EffectiveConceptConstraints+frontmatterConstraints r = EffectiveConceptConstraints (List.nub (r ^. #presenceConstraints)) (List.nub (r ^. #timestampOrderConstraints)) (List.nub (r ^. #membershipConstraints)) (List.nub (r ^. #uniqueValuesConstraints)) Map.empty++nestedConstraints :: NestedRules -> EffectiveConceptConstraints+nestedConstraints r = EffectiveConceptConstraints (List.nub (r ^. #presenceConstraints)) (List.nub (r ^. #timestampOrderConstraints)) [] [] Map.empty++mergeConstraints :: EffectiveConceptConstraints -> EffectiveConceptConstraints -> EffectiveConceptConstraints+mergeConstraints a b =+  EffectiveConceptConstraints+    (List.nub (a ^. #presenceConstraints <> b ^. #presenceConstraints))+    (List.nub (a ^. #timestampOrderConstraints <> b ^. #timestampOrderConstraints))+    (List.nub (a ^. #membershipConstraints <> b ^. #membershipConstraints))+    (List.nub (a ^. #uniqueValuesConstraints <> b ^. #uniqueValuesConstraints))+    Map.empty++compiledProfileBaseConstraints :: CompiledProfile -> EffectiveConceptConstraints+compiledProfileBaseConstraints c = c ^. #baseConstraints++compiledProfileConstraintsForType :: CompiledProfile -> Text -> EffectiveConceptConstraints+compiledProfileConstraintsForType c t = Map.findWithDefault (c ^. #baseConstraints) t (c ^. #constraintsByType)++fieldRuleElementConstraints :: EffectiveFieldRule -> EffectiveConceptConstraints+fieldRuleElementConstraints r = r ^. #elementConstraints++fieldRuleObjectConstraints :: EffectiveFieldRule -> EffectiveConceptConstraints+fieldRuleObjectConstraints r = r ^. #objectConstraints++-- | Resolve a selector against the effective map, never against raw declarations.+resolveValueSelector :: Map Text EffectiveFieldRule -> ValueSelector -> Maybe EffectiveFieldRule+resolveValueSelector rules ValueSelector {field = key, member} = do+  parent <- Map.lookup key rules+  case member of+    Nothing -> Just parent+    Just child -> (parent ^. #elementFields <|> parent ^. #objectFields) >>= Map.lookup child++constraintErrors :: Maybe Text -> Maybe Text -> Map Text EffectiveFieldRule -> EffectiveConceptConstraints -> [ProfileDefinitionError]+constraintErrors scope parent rules c =+  concatMap checkPresence (c ^. #presenceConstraints)+    <> concatMap checkTime (c ^. #timestampOrderConstraints)+    <> concatMap checkMembership (c ^. #membershipConstraints)+    <> concatMap checkUnique (c ^. #uniqueValuesConstraints)+    <> concat+      [ constraintErrors scope (Just key) members constraints+      | (key, r) <- Map.toList rules,+        (Just members, constraints) <- [(r ^. #elementFields, r ^. #elementConstraints), (r ^. #objectFields, r ^. #objectConstraints)]+      ]+  where+    err sel reason = [InvalidConceptConstraint scope parent sel reason]+    nameOK t = not (Text.null (Text.strip t)) && not (Text.any (`elem` (".[]" :: String)) t)+    checkSelector textOnly target sel =+      if not (nameOK (sel ^. #field)) || maybe False (not . nameOK) (sel ^. #member)+        then err sel "selector names must be nonblank field names without traversal"+        else+          if (isJust parent || target) && isJust (sel ^. #member)+            then err sel "this scope requires a sibling selector"+            else case resolveValueSelector rules sel of+              Nothing -> err sel "selector is not declared"+              Just r ->+                [ InvalidConceptConstraint scope parent sel "relation operand must be a scalar or list text leaf"+                | textOnly && (r ^. #cardinality `notElem` [Scalar, List] || isJust (r ^. #elementFields) || isJust (r ^. #objectFields) || r ^. #format `elem` map Just [Integer, NonNegativeInteger, FiniteDecimal, Boolean])+                ]+    checkPresence p =+      [InvalidConceptConstraint scope parent (ValueSelector "" Nothing) "presence constraint needs a target" | null (p ^. #requireAll <> p ^. #requireAny)]+        <> concatMap (checkSelector False False) (p ^. #whenAnyPresent)+        <> concatMap (checkSelector False True) (p ^. #requireAll <> p ^. #requireAny)+        <> concat [err s "duplicate presence selector" | xs <- [p ^. #whenAnyPresent, p ^. #requireAll, p ^. #requireAny], s <- List.nub xs, length (filter (== s) xs) > 1]+        <> case p ^. #when of+          Nothing -> []+          Just gate ->+            let sel = ValueSelector (gate ^. #field) Nothing+             in case Map.lookup (gate ^. #field) rules of+                  Just r | r ^. #cardinality == Scalar, not (null (r ^. #allowedValues)), not (null (gate ^. #hasValue)), all (`elem` r ^. #allowedValues) (gate ^. #hasValue) -> []+                  _ -> err sel "when requires a declared scalar closed vocabulary and reachable nonempty values"+    checkTime t =+      let a = ValueSelector (t ^. #before) Nothing; b = ValueSelector (t ^. #after) Nothing+       in concatMap (checkSelector False True) [a, b]+            <> [ InvalidConceptConstraint scope parent a "timestamp endpoints must be distinct scalar rfc3339-utc fields"+               | a == b || any (\sel -> maybe True (\r -> r ^. #cardinality /= Scalar || r ^. #format /= Just Rfc3339Utc) (resolveValueSelector rules sel)) [a, b]+               ]+    checkMembership m =+      concatMap (checkSelector True False) [m ^. #source, m ^. #target]+        <> [InvalidConceptConstraint scope parent (m ^. #source) "membership operands must differ" | m ^. #source == m ^. #target]+    checkUnique u =+      concatMap (checkSelector True False) (u ^. #selectors)+        <> [InvalidConceptConstraint scope parent (ValueSelector "" Nothing) "uniqueness needs at least two distinct selectors" | length (u ^. #selectors) < 2 || length (List.nub (u ^. #selectors)) /= length (u ^. #selectors)]++-- | Whole located values, preserving both parent-record and leaf-list indices.+locateSelector :: (Text -> FieldPath) -> (Text -> Maybe Value) -> Map Text EffectiveFieldRule -> ValueSelector -> [(FieldPath, EffectiveFieldRule, Value)]+locateSelector build lookupValue rules sel =+  case (Map.lookup key rules, lookupValue key, sel ^. #member) of+    (Just r, Just value, Nothing) -> [(build key, r, value)]+    (Just r, Just (Aeson.Object members), Just child) | Just rs <- r ^. #objectFields -> childValue (appendPath (build key) (FieldName child)) rs child members+    (Just r, Just (Array values), Just child)+      | Just rs <- r ^. #elementFields ->+          concat [childValue (appendPath (appendPath (build key) (ArrayIndex i)) (FieldName child)) rs child members | (i, Aeson.Object members) <- zip [0 ..] (Vector.toList values)]+    _ -> []+  where+    key = sel ^. #field+    childValue path rs child members = [(path, r, v) | Just r <- [Map.lookup child rs], Just v <- [Aeson.KeyMap.lookup (Aeson.Key.fromText child) members]]++appendPath :: FieldPath -> FieldPathSegment -> FieldPath+appendPath (FieldPath xs) x = FieldPath (xs <> (x :| []))++validateConceptConstraints :: ConceptId -> (Text -> FieldPath) -> (Text -> Maybe Value) -> Map Text EffectiveFieldRule -> EffectiveConceptConstraints -> [ProfileViolation]+validateConceptConstraints cid build lookupValue rules c =+  List.nub $+    concatMap presence (c ^. #presenceConstraints)+      <> concatMap timeOrder (c ^. #timestampOrderConstraints)+      <> concatMap membership (c ^. #membershipConstraints)+      <> concatMap unique (c ^. #uniqueValuesConstraints)+  where+    locate sel = [(path, resolved, value) | (path, _, value) <- locateSelector build lookupValue rules sel, Just resolved <- [Map.lookup sel (c ^. #resolvedSelectors)]]+    present s = any (\(_, r, v) -> case evaluateFieldValue r (Just v) of FieldPresent _ -> True; _ -> False) (locate s)+    malformed s = any (\(_, r, v) -> case evaluateFieldValue r (Just v) of FieldWrongShape _ -> True; _ -> False) (locate s)+    presence p =+      let gated = maybe True (\g -> case lookupValue (g ^. #field) of Just (String v) -> v `elem` g ^. #hasValue; _ -> False) (p ^. #when)+          triggered = null (p ^. #whenAnyPresent) || any present (p ^. #whenAnyPresent)+       in if not (gated && triggered)+            then []+            else+              [ConstraintPresenceMissing cid (build (s ^. #field)) (p ^. #when) | s <- p ^. #requireAll, not (present s), not (malformed s)]+                <> [ConstraintAlternativeMissing cid (map (build . (^. #field)) (p ^. #requireAny)) (p ^. #when) | not (null (p ^. #requireAny)), not (any present (p ^. #requireAny)), not (any malformed (p ^. #requireAny))]+    timestamp key = do+      String v <- lookupValue key+      if valueMatchesFormat Rfc3339Utc (String v) then iso8601ParseM (Text.unpack v) else Nothing+    timeOrder t = [TimestampOrderViolation cid (build (t ^. #before)) (build (t ^. #after)) | Just a <- [timestamp (t ^. #before) :: Maybe UTCTime], Just b <- [timestamp (t ^. #after)], a >= b]+    occurrences sel = concatMap project (locate sel)+    project (path, r, v) = case (r ^. #cardinality, v) of+      (List, Array vs) -> [(appendPath path (ArrayIndex i), r, x) | (i, x) <- zip [0 ..] (Vector.toList vs)]+      (Scalar, _) -> [(path, r, v)]+      _ -> [] -- ordinary cardinality check owns this failure+    usable sel = [(path, v) | (path, r, String v) <- occurrences sel, not (Text.null (Text.strip v)), null (r ^. #allowedValues) || valueMatchesVocabulary (r ^. #allowedValues) (String v), maybe True (\f -> valueMatchesFormat f (String v)) (r ^. #format)]+    bad sel =+      [ TextOperandMismatch cid path value+      | (path, r, value) <- occurrences sel,+        case value of String _ -> False; _ -> True,+        ordinaryAccepts r value+      ]+    ordinaryAccepts r v = case evaluateFieldValue (r & #cardinality .~ Scalar) (Just v) of+      FieldWrongShape _ | r ^. #cardinality /= List -> False+      _ ->+        (null (r ^. #allowedValues) || valueMatchesVocabulary (r ^. #allowedValues) v)+          && maybe True (`valueMatchesFormat` v) (r ^. #format)+          && not (isJust (r ^. #reference) || isJust (r ^. #path))+    membership m =+      bad (m ^. #source)+        <> bad (m ^. #target)+        <> [MembershipValueMissing cid path value (m ^. #target) | (path, value) <- usable (m ^. #source), value `notElem` map snd (usable (m ^. #target))]+    unique u = concatMap bad (u ^. #selectors) <> snd (List.foldl' add (Map.empty, []) (concatMap usable (u ^. #selectors)))+    add (seen, errors) (path, value) = case Map.lookup value seen of+      Nothing -> (Map.insert value path seen, errors)+      Just original -> (seen, errors <> [DuplicateSelectedValue cid path value original])++-- | Shared, deterministic prose for both declared and effective constraints.+renderConceptConstraints :: EffectiveConceptConstraints -> [Text]+renderConceptConstraints c =+  category "Presence constraints" (map presence (c ^. #presenceConstraints))+    <> category "Timestamp order constraints" [t ^. #before <> " < " <> t ^. #after | t <- c ^. #timestampOrderConstraints]+    <> category "Membership constraints (text operands)" [selector (m ^. #source) <> " in " <> selector (m ^. #target) | m <- c ^. #membershipConstraints]+    <> category "Unique values constraints (text operands)" [Text.intercalate ", " (map selector (u ^. #selectors)) | u <- c ^. #uniqueValuesConstraints]+  where+    category label [] = [label <> ": none"]+    category label values = [label <> ": " <> Text.intercalate "; " values]+    selector = renderValueSelector+    presence p =+      "when "+        <> maybe "always" (\g -> g ^. #field <> " in [" <> Text.intercalate ", " (g ^. #hasValue) <> "]") (p ^. #when)+        <> "; any present ["+        <> Text.intercalate ", " (map selector (p ^. #whenAnyPresent))+        <> "] (empty means no presence trigger)"+        <> "; require all ["+        <> Text.intercalate ", " (map selector (p ^. #requireAll))+        <> "]"+        <> "; require any ["+        <> Text.intercalate ", " (map selector (p ^. #requireAny))+        <> "]"++normalizeRecordShapes :: EffectiveFieldRule -> EffectiveFieldRule+normalizeRecordShapes r = case (r ^. #elementFields, r ^. #objectFields) of+  (Just a, Just b) ->+    let members = mergeRules a b+        constraints = resolveConstraints members (mergeConstraints (r ^. #elementConstraints) (r ^. #objectConstraints))+     in r+          & #elementFields+          .~ Just members+          & #objectFields+          .~ Just members+          & #elementConstraints+          .~ constraints+          & #objectConstraints+          .~ constraints+  _ -> r++-- | Resolved leaf rules for every selector and condition gate in this scope.+-- Keys preserve the public bounded locations; values are read-only effective rules.+conceptResolvedSelectors :: EffectiveConceptConstraints -> Map ValueSelector EffectiveFieldRule+conceptResolvedSelectors c = c ^. #resolvedSelectors++resolveConstraints :: Map Text EffectiveFieldRule -> EffectiveConceptConstraints -> EffectiveConceptConstraints+resolveConstraints rules c =+  c+    & #resolvedSelectors+    .~ Map.fromList+      [(s, r) | s <- List.nub allSelectors, Just r <- [resolveValueSelector rules s]]+  where+    sibling key = ValueSelector key Nothing+    allSelectors =+      concat [p ^. #whenAnyPresent <> p ^. #requireAll <> p ^. #requireAny <> maybe [] (\g -> [sibling (g ^. #field)]) (p ^. #when) | p <- c ^. #presenceConstraints]+        <> concat [[sibling (t ^. #before), sibling (t ^. #after)] | t <- c ^. #timestampOrderConstraints]+        <> concat [[m ^. #source, m ^. #target] | m <- c ^. #membershipConstraints]+        <> concatMap (^. #selectors) (c ^. #uniqueValuesConstraints)++-- | Display a bounded declaration location, as distinct from an indexed value path.+renderValueSelector :: ValueSelector -> Text+renderValueSelector s = s ^. #field <> maybe "" (\m -> "[]." <> m) (s ^. #member)
+ src/Okf/Profile/Bootstrap.hs view
@@ -0,0 +1,169 @@+{-# LANGUAGE PackageImports #-}++-- | Render an adoption descriptor without writing the destination bundle.+module Okf.Profile.Bootstrap+  ( DescriptorImport (..),+    BootstrapError (..),+    descriptorFileName,+    descriptorImportFor,+    renderBootstrapDescriptor,+    renderBootstrapError,+    relativeImportPath,+    bootstrapOkfVersion,+  )+where++import Control.Exception (SomeAsyncException, SomeException, catch, fromException, throwIO)+import Data.Foldable (toList)+import Data.Maybe (catMaybes)+import Data.Text qualified as Text+import Dhall.Core qualified as D+import Dhall.Freeze qualified as D+import Dhall.Parser qualified as D+import Dhall.Src (Src)+import Okf.Index (OkfVersion, parseOkfVersion)+import Okf.Prelude+import Okf.Profile (ProfileSpec)+import Okf.Profile.Registry+import System.Directory (canonicalizePath)+import System.FilePath (joinPath, normalise, splitDirectories, takeDirectory, takeFileName)+import "generic-lens" Data.Generics.Labels ()++data DescriptorImport+  = ImportRegistryFile !FilePath !Text+  | ImportRegistryExpression !Text !Text+  | ImportDescriptorFile !FilePath+  deriving stock (Generic, Eq, Show)++data BootstrapError+  = RelativeExpressionImport !Text+  | DescriptorParseError !Text+  | DescriptorFreezeError !Text+  deriving stock (Generic, Eq, Show)++descriptorFileName :: FilePath+descriptorFileName = "profile.dhall"++descriptorImportFor :: ProfileSource -> Text -> DescriptorImport+descriptorImportFor source export = case source of+  RegistrySource _ (RegistryFile path) -> ImportRegistryFile path export+  RegistrySource _ (RegistryExpression expression) -> ImportRegistryExpression expression export+  DescriptorSource path -> ImportDescriptorFile path++-- | Inputs are absolute, physically resolved, normalized paths.+relativeImportPath :: FilePath -> FilePath -> FilePath+relativeImportPath base target =+  let (remainingBase, remainingTarget) = dropCommon (splitDirectories base) (splitDirectories target)+      parents = replicate (length remainingBase) ".."+   in joinPath ((if null parents then ["."] else parents) <> remainingTarget)+  where+    dropCommon (x : xs) (y : ys) | x == y = dropCommon xs ys+    dropCommon xs ys = (xs, ys)++renderBootstrapDescriptor :: FilePath -> DescriptorImport -> IO (Either BootstrapError Text)+renderBootstrapDescriptor destination source = handleFailure $ do+  base <- normalise <$> canonicalizePath destination+  prepared <- case source of+    ImportRegistryExpression expression _ -> pure $ case D.exprFromText "registry" expression of+      Left _ -> Left (DescriptorParseError "the registry expression is not valid Dhall")+      Right expr -> case concatMap relativeImports (toList expr) of+        bad : _ -> Left (RelativeExpressionImport (D.pretty bad))+        [] -> Right (expr, expression)+    ImportRegistryFile path _ -> Right <$> localExpression base path+    ImportDescriptorFile path -> Right <$> localExpression base path+  case prepared of+    Left err -> pure (Left err)+    Right (expression, reference) -> do+      frozen <- traverse (freeze base) expression+      let (export, body) = case source of+            ImportRegistryFile _ selected -> (selected, registryBody selected frozen)+            ImportRegistryExpression _ selected -> (selected, registryBody selected frozen)+            ImportDescriptorFile _ -> ("(descriptor)", frozen)+          comments =+            [ "OKF profile descriptor written by `okf profile init`.",+              "",+              "Profile: " <> export,+              "Source:  " <> reference,+              ""+            ]+              <> guidance source+      pure (Right (Text.unlines (map commentLine (concatMap (Text.splitOn "\n") comments)) <> D.pretty body <> "\n"))+  where+    commentLine line = case Text.dropWhileEnd (\c -> c == ' ' || c == '\t') line of+      "" -> "--"+      text -> "-- " <> text+    handleFailure action =+      action `catch` \(err :: SomeException) ->+        case fromException err :: Maybe SomeAsyncException of+          Just _ -> throwIO err+          Nothing -> pure (Left (DescriptorFreezeError "could not prepare or freeze the descriptor; check source paths, network access, and integrity hashes"))++localExpression :: FilePath -> FilePath -> IO (D.Expr Src D.Import, Text)+localExpression base path = do+  target <- normalise <$> canonicalizePath path+  let relative = relativeImportPath base target+      pathParts = splitDirectories (takeDirectory relative)+      (prefix, directories) = case pathParts of+        ".." : rest -> (D.Parent, rest)+        "." : rest -> (D.Here, rest)+        _ -> (D.Here, pathParts)+      file = D.File (D.Directory (reverse (map Text.pack directories))) (Text.pack (takeFileName relative))+      expression = D.Embed (D.Import (D.ImportHashed Nothing (D.Local prefix file)) D.Code)+  pure (expression, D.pretty expression)++-- URL headers contain expressions outside the ordinary Expr traversal.+relativeImports :: D.Import -> [D.Import]+relativeImports imp = case D.importType (D.importHashed imp) of+  D.Local D.Here _ -> [imp]+  D.Local D.Parent _ -> [imp]+  D.Remote url -> maybe [] (concatMap relativeImports . toList) (D.headers url)+  _ -> []++freeze :: FilePath -> D.Import -> IO D.Import+freeze base imp = case D.importHashed imp of+  D.ImportHashed Nothing (D.Remote _) | D.importMode imp /= D.Location -> D.freezeRemoteImport base imp+  _ -> pure imp++registryBody :: Text -> D.Expr Src D.Import -> D.Expr Src D.Import+registryBody export expression =+  D.Let (D.makeBinding "registry" expression) $+    foldl+      (\body segment -> D.Field body (D.makeFieldSelection segment))+      (D.Var (D.V "registry" 0))+      (if Text.null export then [] else Text.splitOn "." export)++guidance :: DescriptorImport -> [Text]+guidance = \case+  ImportRegistryFile {} -> local "registry"+  ImportDescriptorFile {} -> local "profile descriptor"+  ImportRegistryExpression expression _+    | expression == defaultRegistryReference ->+        [ "The registry import is pinned by release and frozen with a sha256 integrity",+          "hash. To move to a newer release, change the tag, delete the sha256 line,",+          "and run `dhall freeze profile.dhall`. Never hand-write a sha256 value.",+          "A pin move can change what the profile demands; the okf-profiles Seihou",+          "migration blueprints in mori://shinzui/okf-profiles describe each release."+        ]+    | otherwise ->+        [ "Existing hashes are preserved and unhashed remote value imports are frozen.",+          "Local and environment inputs remain live; this is not a portable snapshot.",+          "To update remote imports, remove their hashes and run `dhall freeze profile.dhall`.",+          "Never hand-write a sha256 value."+        ]+  where+    local label =+      [ "The " <> label <> " is imported from a local path relative to this file and is not frozen.",+        "This is not a portable snapshot; loading its own imports may require network access."+      ]++renderBootstrapError :: BootstrapError -> Text+renderBootstrapError = \case+  RelativeExpressionImport imp ->+    "cwd-relative registry expression import " <> imp <> "; pass the registry as a file or directory path so okf can re-relativize it, or use an absolute path"+  DescriptorParseError message -> "descriptor parse failed: " <> message+  DescriptorFreezeError message -> "descriptor freeze failed: " <> message++bootstrapOkfVersion :: Maybe OkfVersion -> ProfileSpec -> Maybe OkfVersion+bootstrapOkfVersion existing spec = case catMaybes [existing, (spec ^. #requireBundleVersion) >>= parseOkfVersion, parseOkfVersion (spec ^. #okfVersion)] of+  [] -> Nothing+  versions -> Just (maximum versions)
src/Okf/Profile/Discovery.hs view
@@ -14,7 +14,7 @@   ) where -import Control.Exception (Exception, SomeException, catch, throw)+import Control.Exception (Exception, SomeException, throw) import Control.Monad (filterM) import Data.List qualified as List import Data.Text qualified as Text@@ -24,6 +24,7 @@ import Dhall.Parser qualified import Dhall.TypeCheck qualified import Okf.Discovery (isSearchableDirectory, listDirectorySafe)+import Okf.Exception (catchSynchronous) import Okf.Prelude import Okf.Profile (ProfileSpec, decodeProfileExpr) import System.Directory (doesFileExist, pathIsSymbolicLink)@@ -105,7 +106,7 @@ -- network request. The file is parsed exactly once before import resolution. loadProfileDescriptorWithoutNetwork :: FilePath -> IO (Either Text ProfileSpec) loadProfileDescriptorWithoutNetwork path =-  action `catch` \(exception :: SomeException) -> pure (Left (Text.pack (show exception)))+  action `catchSynchronous` \(exception :: SomeException) -> pure (Left (Text.pack (show exception)))   where     action = do       contents <- Text.IO.readFile path@@ -136,4 +137,4 @@  safelyFalse :: IO Bool -> IO Bool safelyFalse action =-  action `catch` \(_ :: SomeException) -> pure False+  action `catchSynchronous` \(_ :: SomeException) -> pure False
src/Okf/Profile/Documentation.hs view
@@ -283,6 +283,8 @@                "type's rules, which is the form that actually applies.",                ""              ]+          <> map ("- " <>) (renderConceptConstraints (compiledProfileBaseConstraints compiled))+          <> [""]           <> baseRuleLines           <> [ "## Concept types",                ""@@ -377,6 +379,8 @@                "the profile-wide rule and this type's own rule, already merged.",                ""              ]+          <> map ("- " <>) (renderConceptConstraints (compiledProfileConstraintsForType compiled typeName))+          <> [""]           <> group "Required" (Map.toAscList (Map.filter ((== PresenceRequired) . presenceClassOf) rules))           <> group "Recommended" (Map.toAscList (Map.filter ((== PresenceRecommended) . presenceClassOf) rules))           <> group "Optional" (Map.toAscList (Map.filter ((== PresenceOptional) . presenceClassOf) rules))@@ -431,13 +435,17 @@         "- Format: " <> maybe "none" renderFieldFormatName (fieldRuleFormat rule),         "- Reference: " <> maybe "none" renderReference (fieldRuleReference rule),         "- Path: " <> maybe "none" renderPathRule (fieldRulePath rule),-        "- Unique by: " <> maybe "none" code (fieldRuleUniqueBy rule)+        "- Unique by: " <> maybe "none" code (fieldRuleUniqueBy rule),+        "- Object field names: " <> closureName (fieldRuleObjectAllowsUnknownFields rule),+        "- Element field names: " <> closureName (fieldRuleElementAllowsUnknownFields rule)       ]         <> conditionBullets         <> objectFieldBullets         <> elementFieldBullets         <> strictNote +    closureName = maybe "none" (\open -> if open then "open" else "closed")+     conditionBullets =       case [clause | clause <- fieldRulePresenceClauses rule, isJust (presenceClauseCondition clause)] of         [] -> ["- Condition: none"]@@ -458,6 +466,7 @@         Just members ->           ["- Object fields:"]             <> ["    - " <> renderElementField memberKey memberRule | (memberKey, memberRule) <- Map.toAscList members]+            <> map ("    - " <>) (take 2 (renderConceptConstraints (fieldRuleObjectConstraints rule)))      elementFieldBullets =       case fieldRuleElementFields rule of@@ -465,6 +474,7 @@         Just nested ->           ["- Element fields:"]             <> ["    - " <> renderElementField nestedKey nestedRule | (nestedKey, nestedRule) <- Map.toAscList nested]+            <> (if isJust (fieldRuleObjectFields rule) then [] else map ("    - " <>) (take 2 (renderConceptConstraints (fieldRuleElementConstraints rule))))      strictNote =       case presenceClassOf rule of
src/Okf/Profile/Registry.hs view
@@ -46,7 +46,7 @@   ) where -import Control.Exception (SomeException, catch, fromException)+import Control.Exception (SomeException, fromException) import Data.List qualified as List import Data.Text qualified as Text import Data.Text.IO qualified as Text.IO@@ -58,6 +58,7 @@ import Dhall.Parser qualified as Dhall.Parser import Dhall.Src (Src) import Dhall.TypeCheck qualified as Dhall.TypeCheck+import Okf.Exception (catchSynchronous) import Okf.Prelude import Okf.Profile (ProfileSpec, decodeProfileExpr) import Okf.Profile.Discovery (loadProfileDescriptorWithoutNetwork)@@ -189,8 +190,8 @@ -- newer tag means changing the URL and the hash together. defaultRegistryReference :: Text defaultRegistryReference =-  "https://raw.githubusercontent.com/shinzui/okf-profiles/v0.14.0/package.dhall\-  \ sha256:87d2e4076b2491ee608ac1c7a28b24156ba2634f2b09de49ad4ba79f039acf50"+  "https://raw.githubusercontent.com/shinzui/okf-profiles/v0.25.0/package.dhall\+  \ sha256:ec74cc6f7b8ee1a5af81ee7fc8804f35cf2c9ba4010671d9e881da72eb6719d3"  -- | How an entry with an empty export path is displayed. rootExportLabel :: Text@@ -295,7 +296,7 @@     Just registryError -> pure (Left registryError)     Nothing ->       (Right . registryEntries <$> evaluateRef reference)-        `catch` \(exception :: SomeException) ->+        `catchSynchronous` \(exception :: SomeException) ->           pure (Left (classifyRegistryException exception))  registryReferencePreflight :: RegistryRef -> IO (Maybe RegistryLoadError)
+ src/Okf/Profile/Sweep.hs view
@@ -0,0 +1,1432 @@+-- | Load-bearing sweeps of a profile against its own test suite.+--+-- A profile catalog tests each descriptor with acceptance bundles that must pass+-- and rejection cases that must each fail for one reason. A /sweep/ asks the+-- converse question: weaken one rule one way (a /relaxation/), and does some+-- rejection case notice? A rule no case notices is not load-bearing, and the+-- suite has a gap.+--+-- The sweep relaxes the decoded 'ProfileSpec' in memory and recompiles it, per+-- [ADR 5](docs/adr/5-compile-profile-rules-before-validation.md): a relaxation+-- changes what the author wrote, and compilation decides what it means. Core+-- validation and log staleness do not depend on the profile, so every bundle is+-- loaded and checked once ('loadSuite', 'checkBaseline') and each relaxation+-- re-runs only the pure profile check ('observeRelaxation').+--+-- A case /meets its expectation/ under the predicate of the okf-profiles+-- catalog's @scripts\/profile_fixture_cases.py@: run without strict authoring, it+-- produces exactly the expected number of @profile: @ deviation lines and at+-- least one of them contains the expected field name. The predicate compares+-- rendered lines, and rendering belongs to the CLI, so the caller supplies the+-- renderer as a 'Render'.+module Okf.Profile.Sweep+  ( -- * Rule identity+    RuleScope (..),+    PresenceList (..),+    NestedContainer (..),+    RuleLocation (..),+    renderRuleLocation,++    -- * Relaxations+    RelaxationKind (..),+    TypeAttribute (..),+    KindSet (..),+    renderKindSet,+    parseKindSet,+    RelaxationTarget (..),+    Relaxation (..),+    relaxationId,+    relaxationField,+    relaxationKindName,+    legacyKindName,+    enumerateRelaxations,+    applyRelaxation,++    -- * Suites+    CaseExpectation (..),+    SuiteBundle (..),+    RejectionCase (..),+    Suite (..),+    SuiteError (..),+    loadSuite,+    parseExpectations,++    -- * Evaluation+    Render,+    BaselineFault (..),+    PreparedSuite,+    preparedSuite,+    preparedProfile,+    checkBaseline,+    planRelaxations,+    Observation (..),+    observeRelaxation,+    primaryWitness,+    legacyOutcome,+    compositeUnit,++    -- * Classification+    BehaviourKey,+    behaviourKey,+    withBehaviourKey,+    ExceptionClass (..),+    SweepException (..),+    loadExceptions,+    parseExceptions,+    Outcome (..),+    outcomeName,+    outcomeIsFailing,+    SweepResult (..),+    sweepProfile,+    staleExceptions,+  )+where++import Control.Exception (IOException, try)+import Data.Aeson qualified as Aeson+import Data.Aeson.Decoding.ByteString.Lazy (lbsToTokens)+import Data.Aeson.Decoding.Tokens (TkArray (..), TkRecord (..), Tokens (..))+import Data.Aeson.Key (Key)+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString.Lazy qualified as LazyBytes+import Data.Foldable (toList)+import Data.List qualified as List+import Data.Map.Lazy qualified as LazyMap+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (catMaybes, listToMaybe, mapMaybe)+import Data.Scientific (toBoundedInteger)+import Data.Text qualified as Text+import Okf.Bundle+  ( BundleError,+    BundleInventory,+    Concept,+    LogFile,+    conceptIdOf,+    conceptType,+    walkBundle,+    walkBundleInventory,+    walkLogs,+  )+import Okf.ConceptId (ConceptId)+import Okf.Index (OkfVersion, VersionDeclaration, readBundleVersion)+import Okf.Prelude hiding (List, Object)+import Okf.Profile+  ( Cardinality (..),+    CompiledProfile,+    EffectiveConceptConstraints,+    EffectiveFieldRule,+    FieldCondition,+    FieldFormat (DocumentHandle),+    FieldPath (..),+    FieldPathSegment (..),+    FieldRequirement,+    FieldRule,+    HandleReferenceRule,+    PathReferenceRule,+    ProfileDefinitionError,+    ProfileSpec,+    ProfileViolation (..),+    TypeRule,+    compileProfile,+    compiledProfileBaseConstraints,+    compiledProfileBaseRules,+    compiledProfileConstraintsForType,+    compiledProfileRequiredBundleVersion,+    compiledProfileRulesForType,+    compiledProfileSpec,+    compiledProfileTypeNames,+    fieldRuleAllowedValues,+    fieldRuleCardinality,+    fieldRuleDescription,+    fieldRuleElementAllowsUnknownFields,+    fieldRuleElementConstraints,+    fieldRuleElementFields,+    fieldRuleFormat,+    fieldRuleObjectAllowsUnknownFields,+    fieldRuleObjectConstraints,+    fieldRuleObjectFields,+    fieldRulePath,+    fieldRulePresenceClauses,+    fieldRuleReference,+    fieldRuleUniqueBy,+    presenceClauseCondition,+    presenceClauseRequirement,+    validateProfileVersion,+    validateProfileWith,+  )+import Okf.Validation+  ( BundleValidationError,+    LogStaleness,+    ValidationProfile (..),+    logStaleness,+    validateBundle,+    validateBundleLogs,+  )+import System.FilePath ((</>))++-- | Where a rule is declared: profile-wide, or under one concept type.+data RuleScope = ProfileScope | TypeScope !Text+  deriving stock (Generic, Eq, Ord, Show)++-- | Which presence list of a 'Okf.Profile.FrontmatterRules' or+-- 'Okf.Profile.NestedRules' holds the rule.+data PresenceList = RequiredList | RecommendedList | OptionalList+  deriving stock (Generic, Eq, Ord, Show, Enum, Bounded)++-- | The two nested record shapes a top-level rule can declare.+data NestedContainer = ElementFields | ObjectFields+  deriving stock (Generic, Eq, Ord, Show)++-- | One authored rule. 'Okf.Profile.compileProfile' rejects a field named twice+-- in one list at one scope, so scope, list and field identify a top-level rule,+-- and the optional nested part identifies a member of its element or object+-- record. Nested rules cannot nest further, so there are at most two levels.+data RuleLocation = RuleLocation+  { scope :: !RuleScope,+    list :: !PresenceList,+    field :: !Text,+    nested :: !(Maybe (NestedContainer, PresenceList, Text))+  }+  deriving stock (Generic, Eq, Ord, Show)++-- | @profile/required/status@, or+-- @type:Objective/required/keyResults/elementFields/required/id@.+renderRuleLocation :: RuleLocation -> Text+renderRuleLocation RuleLocation {scope, list = presenceList, field = fieldName, nested} =+  Text.intercalate "/" $+    [renderScope scope, renderPresenceList presenceList, fieldName]+      <> maybe [] (\(container, innerList, innerField) -> [renderContainer container, renderPresenceList innerList, innerField]) nested++renderScope :: RuleScope -> Text+renderScope = \case+  ProfileScope -> "profile"+  TypeScope typeName -> "type:" <> typeName++renderPresenceList :: PresenceList -> Text+renderPresenceList = \case+  RequiredList -> "required"+  RecommendedList -> "recommended"+  OptionalList -> "optional"++renderContainer :: NestedContainer -> Text+renderContainer = \case+  ElementFields -> "elementFields"+  ObjectFields -> "objectFields"++-- | A type-scope attribute that is not a frontmatter rule.+data TypeAttribute = PathPattern | ResourceScheme | RequireSchemaSection | SchemaColumns | IdPrefix+  deriving stock (Generic, Eq, Ord, Show)++-- | One way to weaken one rule. The first seven after 'Presence' are the kinds+-- the okf-profiles Python sweep generates ('legacyKindName').+data RelaxationKind+  = -- | remove the rule from its list+    Delete+  | -- | move a @required@ rule to @optional@ at the same scope, dropping only its+    -- @when@ gate, which governs presence alone+    Presence+  | -- | @allowedValues@ to @[]@, which means unconstrained+    ClearVocabulary+  | -- | append one value to a non-empty @allowedValues@+    AdmitValue !Text+  | DropFormat+  | DropUniqueBy+  | -- | @allowSelf@ from 'False' to 'True' inside a handle @reference@+    AllowSelf+  | -- | @allowLocal@ from 'False' to 'True' inside a handle @reference@+    AllowLocal+  | DropExternalUriPattern+  | DropCardinality+  | DropCondition+  | DropPath+  | DropReference+  | DropNested !NestedContainer+  | DropTypeAttribute !TypeAttribute+  | -- | composite unit: a list rule's cardinality to 'Any' and its+    -- @elementFields@ dropped together+    DropListShape+  | -- | composite unit: a type's @idPrefix@ and the @DocumentHandle@ format of+    -- its @idField@ rule dropped together+    DropHandleIdentity+  | -- | composite unit: a list rule's @uniqueBy@ dropped and its key member+    -- demoted to @optional@ together, which the descriptor cannot express one+    -- at a time+    DropUniqueKey+  deriving stock (Generic, Eq, Ord, Show)++-- | Which kinds a sweep enumerates. 'LegacyKinds' reproduces the Python sweep;+-- 'DefaultKinds' adds presence demotion; 'AllKinds' adds every other kind.+data KindSet = LegacyKinds | DefaultKinds | AllKinds+  deriving stock (Generic, Eq, Ord, Show)++renderKindSet :: KindSet -> Text+renderKindSet = \case+  LegacyKinds -> "legacy"+  DefaultKinds -> "default"+  AllKinds -> "all"++parseKindSet :: Text -> Maybe KindSet+parseKindSet = \case+  "legacy" -> Just LegacyKinds+  "default" -> Just DefaultKinds+  "all" -> Just AllKinds+  _ -> Nothing++-- | What a relaxation changes: one authored rule, or one type's attributes.+data RelaxationTarget = RuleTarget !RuleLocation | TypeTarget !Text+  deriving stock (Generic, Eq, Ord, Show)++data Relaxation = Relaxation+  { target :: !RelaxationTarget,+    kind :: !RelaxationKind+  }+  deriving stock (Generic, Eq, Ord, Show)++-- | The target followed by @#@ and the kind, such as+-- @type:Launch/required/launchRef#allowLocal@. Stable: exception manifests name+-- relaxations by it.+relaxationId :: Relaxation -> Text+relaxationId Relaxation {target, kind} = renderTarget target <> "#" <> relaxationKindName kind++renderTarget :: RelaxationTarget -> Text+renderTarget = \case+  RuleTarget location -> renderRuleLocation location+  TypeTarget typeName -> "type:" <> typeName++-- | The innermost field name the relaxation weakens, or the empty text for a+-- type attribute. This is the name the legacy case order prefers.+relaxationField :: Relaxation -> Text+relaxationField Relaxation {target} = case target of+  RuleTarget RuleLocation {field = fieldName, nested} ->+    maybe fieldName (\(_, _, innerField) -> innerField) nested+  TypeTarget _ -> ""++relaxationKindName :: RelaxationKind -> Text+relaxationKindName = \case+  Delete -> "delete"+  Presence -> "presence"+  ClearVocabulary -> "allowedValues"+  AdmitValue value -> "admitValue:" <> value+  DropFormat -> "format"+  DropUniqueBy -> "uniqueBy"+  AllowSelf -> "allowSelf"+  AllowLocal -> "allowLocal"+  DropExternalUriPattern -> "externalUriPattern"+  DropCardinality -> "cardinality"+  DropCondition -> "condition"+  DropPath -> "path"+  DropReference -> "reference"+  DropNested container -> renderContainer container+  DropTypeAttribute attribute -> case attribute of+    PathPattern -> "pathPattern"+    ResourceScheme -> "resourceScheme"+    RequireSchemaSection -> "requireSchemaSection"+    SchemaColumns -> "schemaColumns"+    IdPrefix -> "idPrefix"+  DropListShape -> "listShape"+  DropHandleIdentity -> "handleIdentity"+  DropUniqueKey -> "uniqueKey"++-- | The kind string the Python sweep prints, when the kind is one it generates.+legacyKindName :: RelaxationKind -> Maybe Text+legacyKindName kind = case kind of+  Delete -> Just (relaxationKindName kind)+  ClearVocabulary -> Just (relaxationKindName kind)+  DropFormat -> Just (relaxationKindName kind)+  DropUniqueBy -> Just (relaxationKindName kind)+  AllowSelf -> Just (relaxationKindName kind)+  AllowLocal -> Just (relaxationKindName kind)+  DropExternalUriPattern -> Just (relaxationKindName kind)+  _ -> Nothing++-- | Every applicable relaxation of the authored descriptor, in declaration+-- order: profile-wide rules, then each type's rules followed by its attributes;+-- within one scope the @required@, @recommended@ and @optional@ lists in turn;+-- and within one rule its own relaxations before those of its nested members.+--+-- The legacy kinds follow the Python sweep's applicability: @allowedValues@+-- only when non-empty, @format@ and @uniqueBy@ only when set, @allowSelf@ and+-- @allowLocal@ only when 'False' inside a handle @reference@ (never a @path@),+-- @externalUriPattern@ only when set, and @delete@ always. Unlike the Python+-- sweep, a rule that is the sole element of its list can be deleted.+enumerateRelaxations :: KindSet -> ProfileSpec -> [Relaxation]+enumerateRelaxations kinds spec =+  scopeRelaxations kinds ProfileScope (spec ^. #frontmatter . #required) (spec ^. #frontmatter . #recommended) (spec ^. #frontmatter . #optional)+    <> concat+      [ scopeRelaxations kinds (TypeScope (rule ^. #type_)) (rule ^. #frontmatter . #required) (rule ^. #frontmatter . #recommended) (rule ^. #frontmatter . #optional)+          <> typeRelaxations kinds rule+      | rule <- spec ^. #types+      ]++scopeRelaxations :: KindSet -> RuleScope -> [FieldRule] -> [FieldRule] -> [FieldRule] -> [Relaxation]+scopeRelaxations kinds scope required recommended optional =+  concat+    [ fieldRuleRelaxations kinds (RuleLocation scope presenceList (rule ^. #field) Nothing) rule+    | (presenceList, rules) <- [(RequiredList, required), (RecommendedList, recommended), (OptionalList, optional)],+      rule <- rules+    ]++fieldRuleRelaxations :: KindSet -> RuleLocation -> FieldRule -> [Relaxation]+fieldRuleRelaxations kinds location rule =+  map (Relaxation (RuleTarget location)) (ruleKinds kinds (location ^. #list) facts)+    <> nestedRelaxations ElementFields (rule ^. #elementFields)+    <> nestedRelaxations ObjectFields (rule ^. #objectFields)+  where+    facts =+      RuleFacts+        { allowedValues = rule ^. #allowedValues,+          cardinality = rule ^. #cardinality,+          format = rule ^. #format,+          reference = rule ^. #reference,+          path = rule ^. #path,+          condition = rule ^. #when,+          uniqueBy = rule ^. #uniqueBy,+          hasElementFields = isJust (rule ^. #elementFields),+          hasObjectFields = isJust (rule ^. #objectFields)+        }+    nestedRelaxations container = \case+      Nothing -> []+      Just nestedRules ->+        concat+          [ map+              (Relaxation (RuleTarget (location & #nested ?~ (container, presenceList, member ^. #field))))+              ( ruleKinds+                  kinds+                  presenceList+                  RuleFacts+                    { allowedValues = member ^. #allowedValues,+                      cardinality = member ^. #cardinality,+                      format = member ^. #format,+                      reference = member ^. #reference,+                      path = member ^. #path,+                      condition = member ^. #when,+                      uniqueBy = Nothing,+                      hasElementFields = False,+                      hasObjectFields = False+                    }+              )+          | (presenceList, members) <-+              [ (RequiredList, nestedRules ^. #required),+                (RecommendedList, nestedRules ^. #recommended),+                (OptionalList, nestedRules ^. #optional)+              ],+            member <- members+          ]++-- | What enumeration needs to know about one rule, top-level or nested.+data RuleFacts = RuleFacts+  { allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe FieldFormat),+    reference :: !(Maybe HandleReferenceRule),+    path :: !(Maybe PathReferenceRule),+    condition :: !(Maybe FieldCondition),+    uniqueBy :: !(Maybe Text),+    hasElementFields :: !Bool,+    hasObjectFields :: !Bool+  }+  deriving stock (Generic)++ruleKinds :: KindSet -> PresenceList -> RuleFacts -> [RelaxationKind]+ruleKinds kinds presenceList facts =+  catMaybes+    [ Just Delete,+      Presence <$ guard' (kinds /= LegacyKinds && presenceList == RequiredList),+      ClearVocabulary <$ guard' (not (null (facts ^. #allowedValues))),+      DropFormat <$ facts ^. #format,+      DropUniqueBy <$ facts ^. #uniqueBy,+      AllowSelf <$ guard' (any (not . (^. #allowSelf)) (facts ^. #reference)),+      AllowLocal <$ guard' (any (not . (^. #allowLocal)) (facts ^. #reference)),+      DropExternalUriPattern <$ (facts ^. #reference >>= (^. #externalUriPattern))+    ]+    <> if kinds /= AllKinds+      then []+      else+        catMaybes+          [ DropCardinality <$ guard' (facts ^. #cardinality /= Any),+            DropCondition <$ facts ^. #condition,+            DropPath <$ facts ^. #path,+            DropReference <$ facts ^. #reference,+            DropNested ElementFields <$ guard' (facts ^. #hasElementFields),+            DropNested ObjectFields <$ guard' (facts ^. #hasObjectFields)+          ]++typeRelaxations :: KindSet -> TypeRule -> [Relaxation]+typeRelaxations kinds rule+  | kinds /= AllKinds = []+  | otherwise =+      map (Relaxation (TypeTarget (rule ^. #type_)) . DropTypeAttribute) . catMaybes $+        [ PathPattern <$ rule ^. #pathPattern,+          ResourceScheme <$ rule ^. #resourceScheme,+          RequireSchemaSection <$ guard' (rule ^. #requireSchemaSection),+          SchemaColumns <$ guard' (not (null (rule ^. #schemaColumns))),+          IdPrefix <$ rule ^. #idPrefix+        ]++guard' :: Bool -> Maybe ()+guard' condition = if condition then Just () else Nothing++-- | Perform one relaxation on the authored descriptor. A relaxation whose target+-- does not exist leaves the descriptor unchanged.+applyRelaxation :: Relaxation -> ProfileSpec -> ProfileSpec+applyRelaxation Relaxation {target, kind} spec = case target of+  TypeTarget typeName+    | kind == DropHandleIdentity ->+        spec+          & #types+          . traverse+          . filtered ((== typeName) . (^. #type_))+          %~ \rule ->+            rule+              & #idPrefix+              .~ Nothing+              & #frontmatter+              %~ dropHandleFormat+    | otherwise ->+        spec & #types . traverse . filtered ((== typeName) . (^. #type_)) %~ relaxTypeRule kind+  RuleTarget location@RuleLocation {scope} -> case scope of+    ProfileScope -> spec & #frontmatter %~ relaxScope location kind+    TypeScope typeName ->+      spec & #types . traverse . filtered ((== typeName) . (^. #type_)) . #frontmatter %~ relaxScope location kind+  where+    dropHandleFormat rules = case spec ^. #idField of+      Nothing -> rules+      Just idField ->+        foldr+          (\presenceList -> presenceListOf presenceList . traverse . filtered (named idField) . #format %~ dropHandle)+          rules+          [RequiredList, RecommendedList, OptionalList]+    dropHandle = \case+      Just (DocumentHandle _) -> Nothing+      other -> other++relaxScope ::+  ( HasField' "required" rules [FieldRule],+    HasField' "recommended" rules [FieldRule],+    HasField' "optional" rules [FieldRule]+  ) =>+  RuleLocation ->+  RelaxationKind ->+  rules ->+  rules+relaxScope RuleLocation {list = presenceList, field = fieldName, nested} kind rules = case nested of+  Nothing -> relaxInList presenceList fieldName kind relaxFieldRule rules+  Just (container, innerList, innerField)+    | kind == DropUniqueKey ->+        rules+          & presenceListOf presenceList+          . traverse+          . filtered (named fieldName)+          %~ \rule ->+            rule+              & #uniqueBy+              .~ Nothing+              & containerOf container+              . _Just+              %~ relaxInList innerList innerField Presence relaxCommon+    | otherwise ->+        rules+          & presenceListOf presenceList+          . traverse+          . filtered (named fieldName)+          . containerOf container+          . _Just+          %~ relaxInList innerList innerField kind relaxCommon+  where+    containerOf = \case+      ElementFields -> #elementFields+      ObjectFields -> #objectFields++relaxInList ::+  ( HasField' "required" rules [rule],+    HasField' "recommended" rules [rule],+    HasField' "optional" rules [rule],+    HasField' "field" rule Text,+    HasField' "when" rule (Maybe FieldCondition)+  ) =>+  PresenceList ->+  Text ->+  RelaxationKind ->+  (RelaxationKind -> rule -> rule) ->+  rules ->+  rules+relaxInList presenceList fieldName kind relaxOne rules = case kind of+  Delete -> rules & presenceListOf presenceList %~ filter (not . named fieldName)+  Presence+    | presenceList == RequiredList ->+        let demoted = [rule & field' @"when" .~ Nothing | rule <- rules ^. presenceListOf presenceList, named fieldName rule]+         in rules+              & presenceListOf presenceList+              %~ filter (not . named fieldName)+              & presenceListOf OptionalList+              %~ (<> demoted)+    | otherwise -> rules+  _ -> rules & presenceListOf presenceList . traverse . filtered (named fieldName) %~ relaxOne kind++presenceListOf ::+  ( HasField' "required" rules [rule],+    HasField' "recommended" rules [rule],+    HasField' "optional" rules [rule]+  ) =>+  PresenceList ->+  Lens' rules [rule]+presenceListOf = \case+  RequiredList -> field' @"required"+  RecommendedList -> field' @"recommended"+  OptionalList -> field' @"optional"++named :: (HasField' "field" rule Text) => Text -> rule -> Bool+named fieldName rule = rule ^. field' @"field" == fieldName++relaxFieldRule :: RelaxationKind -> FieldRule -> FieldRule+relaxFieldRule kind rule = case kind of+  DropUniqueBy -> rule & #uniqueBy .~ Nothing+  DropNested ElementFields -> rule & #elementFields .~ Nothing+  DropNested ObjectFields -> rule & #objectFields .~ Nothing+  DropListShape -> rule & #cardinality .~ Any & #elementFields .~ Nothing+  _ -> relaxCommon kind rule++-- | The relaxations a top-level 'FieldRule' and a nested+-- 'Okf.Profile.NestedFieldRule' share.+relaxCommon ::+  ( HasField' "allowedValues" rule [Text],+    HasField' "cardinality" rule Cardinality,+    HasField' "format" rule (Maybe FieldFormat),+    HasField' "reference" rule (Maybe HandleReferenceRule),+    HasField' "path" rule (Maybe PathReferenceRule),+    HasField' "when" rule (Maybe FieldCondition)+  ) =>+  RelaxationKind ->+  rule ->+  rule+relaxCommon kind rule = case kind of+  ClearVocabulary -> rule & field' @"allowedValues" .~ []+  AdmitValue value -> rule & field' @"allowedValues" %~ (<> [value])+  DropFormat -> rule & field' @"format" .~ Nothing+  AllowSelf -> rule & field' @"reference" . _Just . #allowSelf .~ True+  AllowLocal -> rule & field' @"reference" . _Just . #allowLocal .~ True+  DropExternalUriPattern -> rule & field' @"reference" . _Just . #externalUriPattern .~ Nothing+  DropCardinality -> rule & field' @"cardinality" .~ Any+  DropCondition -> rule & field' @"when" .~ Nothing+  DropPath -> rule & field' @"path" .~ Nothing+  DropReference -> rule & field' @"reference" .~ Nothing+  _ -> rule++relaxTypeRule :: RelaxationKind -> TypeRule -> TypeRule+relaxTypeRule kind rule = case kind of+  DropTypeAttribute PathPattern -> rule & #pathPattern .~ Nothing+  DropTypeAttribute ResourceScheme -> rule & #resourceScheme .~ Nothing+  DropTypeAttribute RequireSchemaSection -> rule & #requireSchemaSection .~ False+  DropTypeAttribute SchemaColumns -> rule & #schemaColumns .~ []+  DropTypeAttribute IdPrefix -> rule & #idPrefix .~ Nothing+  _ -> rule++-- | What one rejection case must produce: @count@ deviation lines, at least one+-- of which contains @field@.+data CaseExpectation = CaseExpectation+  { field :: !Text,+    count :: !Int+  }+  deriving stock (Generic, Eq, Show)++-- | One bundle, loaded once: its concepts, file inventory, version declaration+-- and logs.+data SuiteBundle = SuiteBundle+  { path :: !FilePath,+    concepts :: ![Concept],+    inventory :: !BundleInventory,+    declaration :: !VersionDeclaration,+    logs :: ![LogFile]+  }+  deriving stock (Generic)++data RejectionCase = RejectionCase+  { name :: !Text,+    expectation :: !CaseExpectation,+    bundle :: !SuiteBundle+  }+  deriving stock (Generic)++-- | The acceptance bundles and the rejection cases, the cases in the order+-- @expected.json@ lists them.+data Suite = Suite+  { acceptance :: ![SuiteBundle],+    cases :: ![RejectionCase]+  }+  deriving stock (Generic)++data SuiteError+  = -- | a bundle could not be walked or its version declaration read+    SuiteBundleError !FilePath !BundleError+  | -- | @expected.json@ is missing or malformed (path, reason)+    ExpectationsError !FilePath !Text+  deriving stock (Generic, Eq, Show)++-- | Load the acceptance bundles and the cases directory. The cases are the+-- subdirectories @expected.json@ names, in the order it names them; a+-- subdirectory it does not name is not a case.+loadSuite :: [FilePath] -> FilePath -> IO (Either SuiteError Suite)+loadSuite acceptPaths casesDir = do+  let expectedPath = casesDir </> "expected.json"+  read' <- try (LazyBytes.readFile expectedPath)+  case read' of+    Left (readError :: IOException) -> pure (Left (ExpectationsError expectedPath (Text.pack (show readError))))+    Right bytes -> case parseExpectations bytes of+      Left reason -> pure (Left (ExpectationsError expectedPath reason))+      Right expectations -> do+        accepted <- traverse loadSuiteBundle acceptPaths+        rejected <-+          for expectations $ \(caseName, expectation) ->+            fmap (RejectionCase caseName expectation) <$> loadSuiteBundle (casesDir </> Text.unpack caseName)+        pure (Suite <$> sequence accepted <*> sequence rejected)++loadSuiteBundle :: FilePath -> IO (Either SuiteError SuiteBundle)+loadSuiteBundle bundlePath = do+  concepts <- walkBundle bundlePath+  inventory <- walkBundleInventory bundlePath+  declaration <- readBundleVersion bundlePath+  logs <- walkLogs bundlePath+  pure . first (SuiteBundleError bundlePath) $+    SuiteBundle bundlePath <$> concepts <*> inventory <*> declaration <*> logs++-- | Read @expected.json@: an object mapping each case name either to the field+-- name its diagnostic must contain, or to @{"field": …, "diagnostics": N}@.+--+-- Aeson's object type does not keep key order, and the legacy witness is the+-- first case that notices, so the order is read from the token stream and the+-- values from the decoded object. A repeated key keeps its first position.+parseExpectations :: LazyBytes.ByteString -> Either Text [(Text, CaseExpectation)]+parseExpectations bytes = do+  value <- first Text.pack (Aeson.eitherDecode bytes)+  entries <- case value of+    Aeson.Object entries -> Right entries+    _ -> Left "expected a JSON object mapping case names to expectations"+  order <- first Text.pack (topLevelKeys (lbsToTokens bytes))+  for (List.nub order) $ \key ->+    let caseName = Key.toText key+     in case KeyMap.lookup key entries of+          Just (String fieldName) -> Right (caseName, CaseExpectation fieldName 1)+          Just (Aeson.Object spec)+            | Just (String fieldName) <- KeyMap.lookup "field" spec,+              Just (Number diagnostics) <- KeyMap.lookup "diagnostics" spec,+              Just count <- toBoundedInteger diagnostics,+              count >= 0 ->+                Right (caseName, CaseExpectation fieldName count)+          _ ->+            Left+              ( "case "+                  <> caseName+                  <> ": expected a field name or {\"field\": …, \"diagnostics\": N}"+              )++topLevelKeys :: Tokens k String -> Either String [Key]+topLevelKeys = \case+  TkRecordOpen record -> keysOf record+  TkErr err -> Left err+  _ -> Left "expected a JSON object"+  where+    keysOf = \case+      TkPair key value -> (key :) <$> (skipValue value >>= keysOf)+      TkRecordEnd _ -> Right []+      TkRecordErr err -> Left err++-- | Skip one JSON value in a token stream, returning what follows it.+skipValue :: Tokens k String -> Either String k+skipValue = \case+  TkLit _ rest -> Right rest+  TkText _ rest -> Right rest+  TkNumber _ rest -> Right rest+  TkArrayOpen items -> skipItems items+  TkRecordOpen pairs -> skipPairs pairs+  TkErr err -> Left err+  where+    skipItems = \case+      TkItem value -> skipValue value >>= skipItems+      TkArrayEnd rest -> Right rest+      TkArrayErr err -> Left err+    skipPairs = \case+      TkPair _ value -> skipValue value >>= skipPairs+      TkRecordEnd rest -> Right rest+      TkRecordErr err -> Left err++-- | How the CLI renders one deviation, given the compiled profile it came from+-- and the bundle's concepts.+type Render = CompiledProfile -> [Concept] -> ProfileViolation -> Text++-- | Why a sweep cannot start: the unrelaxed profile and suite disagree.+data BaselineFault+  = -- | an acceptance bundle fails core validation or has stale logs, which no+    -- relaxation can change+    AcceptanceCoreInvalid !FilePath ![BundleValidationError] ![LogStaleness]+  | -- | an acceptance bundle deviates from the unrelaxed profile (rendered lines)+    AcceptanceProfileDeviations !FilePath ![Text]+  | -- | a case does not meet its expectation under the unrelaxed profile+    -- (case, expectation, rendered deviation lines)+    CaseExpectationUnmet !Text !CaseExpectation ![Text]+  deriving stock (Generic, Eq, Show)++-- | A suite whose baseline holds, with what every relaxation is compared to.+data PreparedSuite = PreparedSuite+  { suite :: !Suite,+    render :: !Render,+    baseline :: !CompiledProfile,+    -- | each case's violations under the unrelaxed profile, in case order+    baselineViolations :: ![[ProfileViolation]],+    keyOf :: !(CompiledProfile -> BehaviourKey),+    baselineKey :: !BehaviourKey+  }+  deriving stock (Generic)++preparedSuite :: PreparedSuite -> Suite+preparedSuite prepared = prepared ^. #suite++preparedProfile :: PreparedSuite -> CompiledProfile+preparedProfile prepared = prepared ^. #baseline++-- | Replace the behaviour key a prepared suite proves inertness with. For tests+-- of the inertness contradiction only: a key that erases too much makes a+-- relaxation that some case notices look inert.+withBehaviourKey :: (CompiledProfile -> BehaviourKey) -> PreparedSuite -> PreparedSuite+withBehaviourKey keyFunction prepared =+  prepared & #keyOf .~ keyFunction & #baselineKey .~ keyFunction (prepared ^. #baseline)++-- | Check the unrelaxed profile against the suite: every acceptance bundle+-- passes as @okf validate --strict --profile-enforce --log-enforce@ decides, and+-- every case meets its expectation. Reports every fault, not only the first.+checkBaseline :: Render -> CompiledProfile -> Suite -> Either (NonEmpty BaselineFault) PreparedSuite+checkBaseline renderViolation compiled suite =+  case acceptanceFaults <> caseFaults of+    firstFault : moreFaults -> Left (firstFault :| moreFaults)+    [] ->+      Right+        PreparedSuite+          { suite,+            render = renderViolation,+            baseline = compiled,+            baselineViolations = caseViolations,+            keyOf = behaviourKey,+            baselineKey = behaviourKey compiled+          }+  where+    acceptanceFaults = concatMap acceptanceFault (suite ^. #acceptance)+    acceptanceFault bundle'+      | not (null coreErrors && null staleness) = [AcceptanceCoreInvalid (bundle' ^. #path) coreErrors staleness]+      | not (null violations) = [AcceptanceProfileDeviations (bundle' ^. #path) (deviationLines renderViolation compiled bundle' violations)]+      | otherwise = []+      where+        coreErrors =+          validateBundle StrictAuthoring (bundle' ^. #declaration) (bundle' ^. #inventory) (bundle' ^. #concepts)+            <> validateBundleLogs (bundle' ^. #logs)+        staleness = logStaleness (bundle' ^. #concepts) (bundle' ^. #logs)+        violations = profileViolations StrictAuthoring compiled bundle'+    caseViolations = [profileViolations PermissiveConformance compiled (rejection ^. #bundle) | rejection <- suite ^. #cases]+    caseFaults =+      [ CaseExpectationUnmet (rejection ^. #name) (rejection ^. #expectation) lines'+      | (rejection, violations) <- zip (suite ^. #cases) caseViolations,+        let lines' = deviationLines renderViolation compiled (rejection ^. #bundle) violations,+        not (meetsExpectation (rejection ^. #expectation) lines')+      ]++-- | The relaxations a sweep evaluates, in order. Outside 'LegacyKinds', an+-- @allowedValues@ relaxation that makes the descriptor invalid (a @when@+-- condition needs the vocabulary) is followed by one @admitValue@ relaxation+-- per distinct value that some case's baseline 'ValueNotInVocabulary' violation+-- reports at that rule, so that the vocabulary can still be shown load-bearing.+planRelaxations :: KindSet -> PreparedSuite -> [Relaxation]+planRelaxations kinds prepared =+  concatMap expand (enumerateRelaxations kinds spec)+  where+    spec = compiledProfileSpec (prepared ^. #baseline)+    expand relaxation@Relaxation {target, kind}+      | kinds /= LegacyKinds,+        kind == ClearVocabulary,+        Left _ <- compileProfile (applyRelaxation relaxation spec) =+          relaxation : [Relaxation target (AdmitValue value) | value <- admissibleValues target]+      | otherwise = [relaxation]+    admissibleValues target =+      List.nub+        [ value+        | (rejection, violations) <- zip (prepared ^. #suite . #cases) (prepared ^. #baselineViolations),+          ValueNotInVocabulary conceptId path _ (String value) <- violations,+          inScope target (conceptTypes rejection) conceptId,+          pathNames path == targetPath target+        ]++-- | What one relaxation did to the suite.+data Observation = Observation+  { -- | non-empty when the relaxed descriptor no longer compiles+    definitionErrors :: ![ProfileDefinitionError],+    -- | acceptance bundles that deviate from the relaxed profile, with their+    -- rendered lines+    acceptanceDeviations :: ![(FilePath, [Text])],+    -- | cases that no longer meet their expectation, in legacy order: cases+    -- expecting the relaxed field first, then the rest in @expected.json@ order+    witnesses :: ![Text],+    -- | cases in which a baseline violation of the relaxation's own kind at the+    -- relaxed rule disappears, whether or not the case still fails otherwise+    facetWitnesses :: ![Text],+    -- | the relaxed profile compiles to the baseline's 'BehaviourKey'+    behaviourUnchanged :: !Bool+  }+  deriving stock (Generic, Eq, Show)++-- | The witness the Python sweep would name: the first in legacy order.+primaryWitness :: Observation -> Maybe Text+primaryWitness observation = listToMaybe (observation ^. #witnesses)++-- | The Python sweep's verdict, with its precedence: a descriptor that does not+-- compile or an acceptance deviation is @acceptance-fails@, then the primary+-- witness, then @UNPROTECTED@.+legacyOutcome :: Observation -> Text+legacyOutcome observation+  | not (null (observation ^. #definitionErrors)) = "acceptance-fails"+  | not (null (observation ^. #acceptanceDeviations)) = "acceptance-fails"+  | Just witness <- primaryWitness observation = "fixture " <> witness+  | otherwise = "UNPROTECTED"++-- | Apply one relaxation, recompile, and evaluate every acceptance bundle and+-- every case. All witnesses are collected, not only the first.+observeRelaxation :: PreparedSuite -> Relaxation -> Observation+observeRelaxation prepared relaxation =+  case compileProfile (applyRelaxation relaxation (compiledProfileSpec (prepared ^. #baseline))) of+    Left errors -> Observation (toList errors) [] [] [] False+    Right compiled ->+      let evaluated =+            [ (rejection, before, after)+            | (rejection, before) <- zip (prepared ^. #suite . #cases) (prepared ^. #baselineViolations),+              let after = profileViolations PermissiveConformance compiled (rejection ^. #bundle)+            ]+          noticed =+            [ (rejection ^. #name, rejection ^. #expectation . #field)+            | (rejection, _, after) <- evaluated,+              not (meetsExpectation (rejection ^. #expectation) (deviationLines renderViolation compiled (rejection ^. #bundle) after))+            ]+       in Observation+            { definitionErrors = [],+              acceptanceDeviations =+                [ (bundle' ^. #path, deviationLines renderViolation compiled bundle' violations)+                | bundle' <- prepared ^. #suite . #acceptance,+                  let violations = profileViolations StrictAuthoring compiled bundle',+                  not (null violations)+                ],+              witnesses = map fst (legacyOrder (relaxationField relaxation) noticed),+              facetWitnesses =+                [ rejection ^. #name+                | (rejection, before, after) <- evaluated,+                  any (\violation -> isFacet (conceptTypes rejection) violation && violation `notElem` after) before+                ],+              behaviourUnchanged = (prepared ^. #keyOf) compiled == prepared ^. #baselineKey+            }+  where+    renderViolation = prepared ^. #render+    facets = kindFacets (relaxation ^. #kind)+    isFacet typesById violation =+      or+        [ facet `elem` facets && inScope (relaxation ^. #target) typesById conceptId && facetPathMatches facet names (targetPath (relaxation ^. #target))+        | (conceptId, facet, names) <- violationFacets violation+        ]++-- | Order (case, expected field) pairs as the Python sweep does: cases+-- expecting the given field first, the rest after, each group in+-- @expected.json@ order (a stable sort).+legacyOrder :: Text -> [(Text, Text)] -> [(Text, Text)]+legacyOrder fieldName = List.sortOn ((/= fieldName) . snd)++conceptTypes :: RejectionCase -> Map ConceptId Text+conceptTypes rejection = Map.fromList [(conceptIdOf concept, conceptType concept) | concept <- rejection ^. #bundle . #concepts]++inScope :: RelaxationTarget -> Map ConceptId Text -> ConceptId -> Bool+inScope target typesById conceptId = case target of+  RuleTarget RuleLocation {scope = ProfileScope} -> True+  RuleTarget RuleLocation {scope = TypeScope typeName} -> Map.lookup conceptId typesById == Just typeName+  TypeTarget typeName -> Map.lookup conceptId typesById == Just typeName++-- | The field names a relaxation's rule governs, outermost first; empty for a+-- type attribute.+targetPath :: RelaxationTarget -> [Text]+targetPath = \case+  RuleTarget RuleLocation {field = fieldName, nested} -> fieldName : maybe [] (\(_, _, innerField) -> [innerField]) nested+  TypeTarget _ -> []++pathNames :: FieldPath -> [Text]+pathNames (FieldPath segments) = [name' | FieldName name' <- toList segments]++-- | Which kind of check a violation reports, so a relaxation can be credited+-- with the disappearance of exactly the checks it weakens.+data Facet+  = MissingFacet+  | VocabularyFacet+  | FormatFacet+  | UniquenessFacet+  | LocalFacet+  | SelfFacet+  | PatternFacet+  | CardinalityFacet+  | ReferenceFacet+  | PathFacet+  | PathPatternFacet+  | ResourceFacet+  | SchemaSectionFacet+  | SchemaColumnsFacet+  | DocumentIdFacet+  deriving stock (Eq, Show)++violationFacets :: ProfileViolation -> [(ConceptId, Facet, [Text])]+violationFacets = \case+  MissingProfileField conceptId key _ -> [(conceptId, MissingFacet, [key])]+  MissingNestedProfileField conceptId path _ -> [(conceptId, MissingFacet, pathNames path)]+  ValueNotInVocabulary conceptId path _ _ -> [(conceptId, VocabularyFacet, pathNames path)]+  ValueFormatMismatch conceptId path _ _ -> [(conceptId, FormatFacet, pathNames path)]+  DuplicateNestedFieldValue conceptId path _ _ -> [(conceptId, UniquenessFacet, pathNames path)]+  CardinalityMismatch conceptId path _ _ -> [(conceptId, CardinalityFacet, pathNames path)]+  LocalDocumentReferenceNotAllowed conceptId path _ -> reference conceptId path [LocalFacet]+  SelfDocumentReference conceptId path _ -> reference conceptId path [SelfFacet, PathFacet]+  ExternalReferencePatternMismatch conceptId path _ _ -> reference conceptId path [PatternFacet]+  DanglingHandleReference conceptId path _ -> reference conceptId path []+  ReferenceHandlePrefixMismatch conceptId path _ _ -> reference conceptId path []+  MalformedDocumentReference conceptId path _ -> reference conceptId path [PathFacet]+  ExternalReferenceSchemeNotAllowed conceptId path _ _ -> reference conceptId path [PathFacet]+  MalformedPathReference conceptId path _ -> [(conceptId, PathFacet, pathNames path)]+  PathEscapesBundle conceptId path _ -> [(conceptId, PathFacet, pathNames path)]+  DanglingPathReference conceptId path _ -> [(conceptId, PathFacet, pathNames path)]+  PathPatternMismatch conceptId _ _ -> [(conceptId, PathPatternFacet, [])]+  MissingResource conceptId _ _ -> [(conceptId, ResourceFacet, [])]+  ResourceSchemeMismatch conceptId _ _ -> [(conceptId, ResourceFacet, [])]+  MissingSchemaSection conceptId _ -> [(conceptId, SchemaSectionFacet, [])]+  SchemaColumnsMismatch conceptId _ _ _ -> [(conceptId, SchemaColumnsFacet, [])]+  MissingDocumentId conceptId _ _ -> [(conceptId, DocumentIdFacet, [])]+  MalformedDocumentId conceptId _ _ -> [(conceptId, DocumentIdFacet, [])]+  _ -> []+  where+    reference conceptId path extra = [(conceptId, facet, pathNames path) | facet <- ReferenceFacet : extra]++kindFacets :: RelaxationKind -> [Facet]+kindFacets = \case+  Delete -> [MissingFacet]+  Presence -> [MissingFacet]+  ClearVocabulary -> [VocabularyFacet]+  AdmitValue _ -> [VocabularyFacet]+  DropFormat -> [FormatFacet]+  DropUniqueBy -> [UniquenessFacet]+  AllowSelf -> [SelfFacet]+  AllowLocal -> [LocalFacet]+  DropExternalUriPattern -> [PatternFacet]+  DropCardinality -> [CardinalityFacet]+  DropCondition -> [MissingFacet]+  DropPath -> [PathFacet]+  DropReference -> [ReferenceFacet]+  DropNested _ -> []+  DropTypeAttribute attribute -> case attribute of+    PathPattern -> [PathPatternFacet]+    ResourceScheme -> [ResourceFacet]+    RequireSchemaSection -> [SchemaSectionFacet]+    SchemaColumns -> [SchemaColumnsFacet]+    IdPrefix -> [DocumentIdFacet]+  DropListShape -> [CardinalityFacet]+  DropHandleIdentity -> [DocumentIdFacet, FormatFacet]+  DropUniqueKey -> [MissingFacet, UniquenessFacet]++-- | A facet violation belongs to a rule when its field names are the rule's;+-- a uniqueness violation names the duplicated member below the list rule, and a+-- type attribute's violations name no field at all.+facetPathMatches :: Facet -> [Text] -> [Text] -> Bool+facetPathMatches facet names rulePath = case facet of+  UniquenessFacet -> rulePath `List.isPrefixOf` names+  _ | null rulePath -> True+  _ -> names == rulePath++profileViolations :: ValidationProfile -> CompiledProfile -> SuiteBundle -> [ProfileViolation]+profileViolations mode compiled bundle' =+  validateProfileVersion (bundle' ^. #declaration) compiled+    <> validateProfileWith (bundle' ^. #inventory) mode compiled (bundle' ^. #concepts)++-- | The deviation lines @okf validate@ prints, as the catalog's harness reads+-- them: each violation is printed behind @profile: @, and a line counts when it+-- starts with that prefix and is not the advisory summary.+deviationLines :: Render -> CompiledProfile -> SuiteBundle -> [ProfileViolation] -> [Text]+deviationLines renderViolation compiled bundle' =+  filter isDeviationLine . concatMap (Text.lines . ("profile: " <>) . renderViolation compiled (bundle' ^. #concepts))+  where+    isDeviationLine line =+      "profile: " `Text.isPrefixOf` line && not ("advisory deviation(s)" `Text.isInfixOf` line)++meetsExpectation :: CaseExpectation -> [Text] -> Bool+meetsExpectation CaseExpectation {field = fieldName, count} lines' =+  length lines' == count && any (fieldName `Text.isInfixOf`) lines'++-- | The relaxation that weakens a whole composite policy unit of which this+-- relaxation weakens one member, per the okf-profiles catalog's ADR-9: a+-- member's effect can be masked by the unit's other members, so a member no+-- case notices is covered when some case notices the unit.+--+-- The units are a handle @reference@ (members @allowLocal@, @allowSelf@ and+-- @externalUriPattern@), a list rule's shape (its 'List' cardinality and its+-- @elementFields@), and a type's handle identity (its @idPrefix@ and the+-- @DocumentHandle@ format of its @idField@ rule). A fourth is okf's own: a+-- list rule's @uniqueBy@ and its key member's presence, because+-- 'Okf.Profile.compileProfile' rejects a @uniqueBy@ key that is not+-- unconditionally required, so deleting or demoting the key alone never+-- compiles.+compositeUnit :: ProfileSpec -> Relaxation -> Maybe Relaxation+compositeUnit spec Relaxation {target, kind} = case (target, kind) of+  (RuleTarget _, AllowLocal) -> Just (Relaxation target DropReference)+  (RuleTarget _, AllowSelf) -> Just (Relaxation target DropReference)+  (RuleTarget _, DropExternalUriPattern) -> Just (Relaxation target DropReference)+  (RuleTarget location@RuleLocation {nested = Nothing}, DropCardinality)+    | Just rule <- topLevelRule spec location,+      rule ^. #cardinality == List,+      isJust (rule ^. #elementFields) ->+        Just (Relaxation target DropListShape)+  (RuleTarget RuleLocation {nested = Nothing}, DropNested ElementFields) -> Just (Relaxation target DropListShape)+  (RuleTarget location@RuleLocation {scope = TypeScope typeName, field = fieldName, nested = Nothing}, DropFormat)+    | spec ^. #idField == Just fieldName,+      Just rule <- topLevelRule spec location,+      Just (DocumentHandle _) <- rule ^. #format,+      typeHasIdPrefix typeName ->+        Just (Relaxation (TypeTarget typeName) DropHandleIdentity)+  (TypeTarget typeName, DropTypeAttribute IdPrefix) -> Just (Relaxation (TypeTarget typeName) DropHandleIdentity)+  (RuleTarget location@RuleLocation {nested = Just (ElementFields, RequiredList, key)}, memberKind)+    | memberKind == Delete || memberKind == Presence,+      Just rule <- topLevelRule spec location,+      rule ^. #uniqueBy == Just key ->+        Just (Relaxation target DropUniqueKey)+  _ -> Nothing+  where+    typeHasIdPrefix typeName = any (\rule -> rule ^. #type_ == typeName && isJust (rule ^. #idPrefix)) (spec ^. #types)++topLevelRule :: ProfileSpec -> RuleLocation -> Maybe FieldRule+topLevelRule spec RuleLocation {scope, list = presenceList, field = fieldName} =+  listToMaybe (filter (named fieldName) (concatMap (^. presenceListOf presenceList) scopes))+  where+    scopes = case scope of+      ProfileScope -> [spec ^. #frontmatter]+      TypeScope typeName -> [rule ^. #frontmatter | rule <- spec ^. #types, rule ^. #type_ == typeName]++-- | What a compiled profile makes the validator do, with what it provably never+-- consults erased, so that two compiled profiles with equal keys produce the+-- same violations on every bundle. Built from the public inspection accessors.+--+-- The erasures, each with the function that proves it:+--+-- * Descriptions and guidance. The validator never reads them; the CLI's+--   renderer reads a field's description only for a missing-field violation,+--   which only a rule with a presence clause produces, so a description is kept+--   exactly when the effective rule has one.+-- * A rule that constrains nothing (no presence clause, no vocabulary, 'Any'+--   cardinality, no format, nested shape, reference, path or uniqueness) in an+--   open record: 'validateProfileWith' checks a present key only against its+--   rule, and reports an undeclared key only when the record is closed.+-- * @allowSelf@ in a handle reference whose effective @allowLocal@ is 'False':+--   @validateReferenceText@ rejects every local handle before it reads+--   @allowSelf@.+-- * @externalUriPattern@ when @externalUriSchemes@ is empty:+--   @validateReferenceText@ reads the pattern only for a URI whose scheme is+--   allowed.+data BehaviourKey = BehaviourKey+  { allowUnknownTypes :: !Bool,+    allowUnknownFields :: !Bool,+    idField :: !(Maybe Text),+    requiredBundleVersion :: !(Maybe OkfVersion),+    typeAttributes :: ![(Text, Maybe Text, Maybe Text, Bool, [Text], Maybe Text)],+    baseRules :: !(Map Text RuleKey),+    baseConstraints :: !EffectiveConceptConstraints,+    typeRules :: ![(Text, Map Text RuleKey, EffectiveConceptConstraints)]+  }+  deriving stock (Generic, Eq, Show)++data RuleKey = RuleKey+  { presence :: ![(FieldRequirement, Maybe FieldCondition)],+    description :: !(Maybe Text),+    allowedValues :: ![Text],+    cardinality :: !Cardinality,+    format :: !(Maybe FieldFormat),+    elementFields :: !(Maybe (Map Text RuleKey)),+    objectFields :: !(Maybe (Map Text RuleKey)),+    elementOpen :: !(Maybe Bool),+    objectOpen :: !(Maybe Bool),+    reference :: !(Maybe HandleReferenceRule),+    path :: !(Maybe PathReferenceRule),+    uniqueBy :: !(Maybe Text),+    elementConstraints :: !EffectiveConceptConstraints,+    objectConstraints :: !EffectiveConceptConstraints+  }+  deriving stock (Generic, Eq, Show)++behaviourKey :: CompiledProfile -> BehaviourKey+behaviourKey compiled =+  BehaviourKey+    { allowUnknownTypes = spec ^. #allowUnknownTypes,+      allowUnknownFields = open,+      idField = spec ^. #idField,+      requiredBundleVersion = compiledProfileRequiredBundleVersion compiled,+      typeAttributes =+        [ (rule ^. #type_, rule ^. #pathPattern, rule ^. #resourceScheme, rule ^. #requireSchemaSection, rule ^. #schemaColumns, rule ^. #idPrefix)+        | rule <- spec ^. #types+        ],+      baseRules = rulesKey open (compiledProfileBaseRules compiled),+      baseConstraints = compiledProfileBaseConstraints compiled,+      typeRules =+        [ (typeName, rulesKey open (compiledProfileRulesForType compiled typeName), compiledProfileConstraintsForType compiled typeName)+        | typeName <- compiledProfileTypeNames compiled+        ]+    }+  where+    spec = compiledProfileSpec compiled+    open = spec ^. #allowUnknownFields++rulesKey :: Bool -> Map Text EffectiveFieldRule -> Map Text RuleKey+rulesKey open = Map.mapMaybe $ \rule ->+  let key = ruleKey rule+   in if open && constrainsNothing key then Nothing else Just key++ruleKey :: EffectiveFieldRule -> RuleKey+ruleKey rule =+  RuleKey+    { presence,+      description = if null presence then Nothing else fieldRuleDescription rule,+      allowedValues = fieldRuleAllowedValues rule,+      cardinality = fieldRuleCardinality rule,+      format = fieldRuleFormat rule,+      elementFields = rulesKey (elementOpen == Just True) <$> fieldRuleElementFields rule,+      objectFields = rulesKey (objectOpen == Just True) <$> fieldRuleObjectFields rule,+      elementOpen,+      objectOpen,+      reference = eraseUnread <$> fieldRuleReference rule,+      path = fieldRulePath rule,+      uniqueBy = fieldRuleUniqueBy rule,+      elementConstraints = fieldRuleElementConstraints rule,+      objectConstraints = fieldRuleObjectConstraints rule+    }+  where+    presence = [(presenceClauseRequirement clause, presenceClauseCondition clause) | clause <- fieldRulePresenceClauses rule]+    elementOpen = fieldRuleElementAllowsUnknownFields rule+    objectOpen = fieldRuleObjectAllowsUnknownFields rule+    eraseUnread policy =+      policy+        & (if policy ^. #allowLocal then id else #allowSelf .~ False)+        & (if null (policy ^. #externalUriSchemes) then #externalUriPattern .~ Nothing else id)++constrainsNothing :: RuleKey -> Bool+constrainsNothing key =+  null (key ^. #presence)+    && null (key ^. #allowedValues)+    && key ^. #cardinality == Any+    && isNothing (key ^. #format)+    && isNothing (key ^. #elementFields)+    && isNothing (key ^. #objectFields)+    && isNothing (key ^. #reference)+    && isNothing (key ^. #path)+    && isNothing (key ^. #uniqueBy)++-- | Why okf cannot decide a relaxation itself, as documented beside the cases.+data ExceptionClass+  = -- | the rule is spliced from a shared family tested in its home profile+    SharedFamily !Text+  | -- | another rule or type attribute governs the same value+    OverlappingRule !Text+  | -- | a known gap, deferred to the named request (a @mori://@ URI)+    Deferred !Text+  deriving stock (Generic, Eq, Show)++data SweepException = SweepException+  { relaxation :: !Text,+    exceptionClass :: !ExceptionClass,+    rationale :: !Text+  }+  deriving stock (Generic, Eq, Show)++loadExceptions :: FilePath -> IO (Either Text [SweepException])+loadExceptions manifestPath = do+  read' <- try (LazyBytes.readFile manifestPath)+  pure $ case read' of+    Left (readError :: IOException) -> Left (Text.pack (show readError))+    Right bytes -> parseExceptions bytes++-- | Read an exception manifest:+-- @{"version": 1, "exceptions": [{"relaxation": ID, "class": C, …, "rationale": R}]}@.+-- The class is closed: @shared-family@ needs @home@, @overlapping-rule@ needs+-- @overlapsWith@, and @deferred@ needs @request@, a @mori://@ URI.+parseExceptions :: LazyBytes.ByteString -> Either Text [SweepException]+parseExceptions bytes = do+  value <- first Text.pack (Aeson.eitherDecode bytes)+  manifest <- case value of+    Aeson.Object manifest -> Right manifest+    _ -> Left "expected a JSON object with version and exceptions"+  case KeyMap.lookup "version" manifest of+    Just (Number 1) -> Right ()+    _ -> Left "unsupported manifest version; expected \"version\": 1"+  entries <- case KeyMap.lookup "exceptions" manifest of+    Just (Array entries) -> Right (toList entries)+    _ -> Left "expected an \"exceptions\" array"+  for (zip [0 :: Int ..] entries) $ \(entryIndex, entry) ->+    first (\reason -> "exceptions[" <> Text.pack (show entryIndex) <> "]: " <> reason) $ case entry of+      Aeson.Object fields -> do+        relaxation <- text fields "relaxation"+        rationale <- text fields "rationale"+        exceptionClass <-+          text fields "class" >>= \case+            "shared-family" -> SharedFamily <$> text fields "home"+            "overlapping-rule" -> OverlappingRule <$> text fields "overlapsWith"+            "deferred" -> do+              request <- text fields "request"+              if "mori://" `Text.isPrefixOf` request then Right (Deferred request) else Left "request must be a mori:// URI"+            other -> Left ("unknown class " <> other <> "; expected shared-family, overlapping-rule or deferred")+        Right (SweepException relaxation exceptionClass rationale)+      _ -> Left "expected an object"+  where+    text fields key = case KeyMap.lookup key fields of+      Just (String value) | not (Text.null (Text.strip value)) -> Right value+      _ -> Left ("missing or empty \"" <> Key.toText key <> "\"")++-- | How one relaxation is classified. The first matching rule decides:+--+-- 1. 'Protected': some case noticed it, and the descriptor still compiles and+--    every acceptance bundle still passes.+-- 2. 'Subsumed': a @delete@ that fails a descriptor or acceptance check, while+--    every other relaxation of the same rule is non-failing.+-- 3. 'Covered' by an @admitValue@: an @allowedValues@ relaxation the+--    descriptor cannot express, while admitting one reported value is noticed.+-- 4. 'DescriptorInvalidOutcome' or 'AcceptanceObservableOutcome'. A+--    descriptor the relaxation cannot express is first 'Covered' when its+--    composite unit is protected (rule 6), or an 'ExceptionOutcome' when the+--    manifest documents it (rule 7).+-- 5. 'Inert': the relaxed profile has the baseline's 'BehaviourKey'.+-- 6. 'Covered' by a composite unit ('compositeUnit') that is protected.+-- 7. 'ExceptionOutcome': no witness, and the manifest documents it.+-- 8. 'Unprotected'.+--+-- 'Contradiction' is okf's own bug: a relaxation with an unchanged behaviour+-- key that some case nevertheless noticed.+data Outcome+  = Protected+  | Subsumed ![Text]+  | -- | the covering relaxation and its witness+    Covered !Text !Text+  | DescriptorInvalidOutcome+  | AcceptanceObservableOutcome+  | Inert !Text+  | ExceptionOutcome !SweepException+  | Unprotected+  | Contradiction+  deriving stock (Generic, Eq, Show)++outcomeName :: Outcome -> Text+outcomeName = \case+  Protected -> "protected"+  Subsumed _ -> "subsumed"+  Covered _ _ -> "covered"+  DescriptorInvalidOutcome -> "descriptor-invalid"+  AcceptanceObservableOutcome -> "acceptance-observable"+  Inert _ -> "inert"+  ExceptionOutcome _ -> "exception"+  Unprotected -> "unprotected"+  Contradiction -> "contradiction"++outcomeIsFailing :: Outcome -> Bool+outcomeIsFailing = \case+  DescriptorInvalidOutcome -> True+  AcceptanceObservableOutcome -> True+  Unprotected -> True+  Contradiction -> True+  _ -> False++data SweepResult = SweepResult+  { relaxation :: !Relaxation,+    observation :: !Observation,+    outcome :: !Outcome+  }+  deriving stock (Generic, Eq, Show)++-- | Evaluate and classify the given relaxations, normally 'planRelaxations' or+-- a filtered part of it, one rule location (or type) at a time. The list is+-- lazy per group: consuming the first group does not force later groups, and a+-- group's results, which may depend on each other, are yielded in the order+-- given. Composite units evaluated to classify a member are reported only+-- through 'Covered'.+sweepProfile :: [SweepException] -> PreparedSuite -> [Relaxation] -> [SweepResult]+sweepProfile exceptions prepared =+  concatMap evaluateGroup . List.groupBy (\left right -> left ^. #target == right ^. #target)+  where+    spec = compiledProfileSpec (prepared ^. #baseline)+    manifest = Map.fromList [(entry ^. #relaxation, entry) | entry <- exceptions]+    -- Lazy maps on purpose: a delete's outcome reads its siblings' outcomes+    -- from the same map, and a unit is observed only if a member asks for it.+    evaluateGroup group =+      let observed = LazyMap.fromList [(relaxation, observeRelaxation prepared relaxation) | relaxation <- group]+          units = LazyMap.fromList [(unit, observeRelaxation prepared unit) | Just unit <- map (compositeUnit spec) group]+          outcomes = LazyMap.mapWithKey classify observed+          classify relaxation observation+            | observation ^. #behaviourUnchanged, not (null (observation ^. #witnesses)) = Contradiction+            | protects observation = Protected+            | relaxation ^. #kind == Delete,+              failsCheck observation,+              all (nonFailing . (outcomes LazyMap.!)) siblings =+                Subsumed (map relaxationId siblings)+            | relaxation ^. #kind == ClearVocabulary,+              not (null (observation ^. #definitionErrors)),+              (admitted, witness) : _ <-+                [ (sibling, witness)+                | sibling@Relaxation {kind = AdmitValue _} <- siblings,+                  Protected <- [outcomes LazyMap.! sibling],+                  Just witness <- [primaryWitness (observed LazyMap.! sibling)]+                ] =+                Covered (relaxationId admitted) witness+            | not (null (observation ^. #definitionErrors)),+              Just covered <- unitCover relaxation =+                covered+            | not (null (observation ^. #definitionErrors)),+              Just entry <- Map.lookup (relaxationId relaxation) manifest =+                ExceptionOutcome entry+            | not (null (observation ^. #definitionErrors)) = DescriptorInvalidOutcome+            | not (null (observation ^. #acceptanceDeviations)) = AcceptanceObservableOutcome+            | observation ^. #behaviourUnchanged = Inert (inertReason relaxation)+            | Just covered <- unitCover relaxation = covered+            | Just entry <- Map.lookup (relaxationId relaxation) manifest = ExceptionOutcome entry+            | otherwise = Unprotected+            where+              siblings = filter (/= relaxation) group+          unitCover relaxation = do+            unit <- compositeUnit spec relaxation+            unitObservation <- LazyMap.lookup unit units+            witness <- primaryWitness unitObservation+            if protects unitObservation then Just (Covered (relaxationId unit) witness) else Nothing+       in [SweepResult relaxation (observed LazyMap.! relaxation) (outcomes LazyMap.! relaxation) | relaxation <- group]+    protects observation =+      not (null (observation ^. #witnesses))+        && null (observation ^. #definitionErrors)+        && null (observation ^. #acceptanceDeviations)+    failsCheck observation =+      not (null (observation ^. #definitionErrors)) || not (null (observation ^. #acceptanceDeviations))+    nonFailing = \case+      Protected -> True+      Inert _ -> True+      Covered _ _ -> True+      ExceptionOutcome _ -> True+      _ -> False++inertReason :: Relaxation -> Text+inertReason Relaxation {kind} = case kind of+  AllowSelf -> "allowSelf is never read while allowLocal is False"+  DropExternalUriPattern -> "externalUriPattern is never read while externalUriSchemes is empty"+  _ -> "the relaxed profile compiles to the same behaviour key as the baseline"++-- | Manifest entries that no longer describe a gap: the entry's relaxation was+-- evaluated and classified as something other than an exception, or it names a+-- relaxation this run's kinds would enumerate and none was. With @onlySome@+-- (an @--only@ run) an entry for a relaxation that was not swept is not stale.+staleExceptions :: KindSet -> Bool -> [SweepException] -> [(Text, Outcome)] -> [SweepException]+staleExceptions kinds onlySome exceptions results =+  filter stale exceptions+  where+    outcomes = Map.fromList results+    stale entry = case Map.lookup (entry ^. #relaxation) outcomes of+      Just (ExceptionOutcome _) -> False+      Just _ -> True+      Nothing -> not onlySome && enumeratedBy (snd (Text.breakOnEnd "#" (entry ^. #relaxation)))+    enumeratedBy kindName+      | kindName `elem` legacyNames = True+      | kindName == "presence" || "admitValue:" `Text.isPrefixOf` kindName = kinds /= LegacyKinds+      | otherwise = kinds == AllKinds+    legacyNames = mapMaybe legacyKindName [Delete, ClearVocabulary, DropFormat, DropUniqueBy, AllowSelf, AllowLocal, DropExternalUriPattern]
src/Okf/Query.hs view
@@ -1,3 +1,4 @@+{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE PackageImports #-}  -- | Selecting concepts out of a bundle by what their frontmatter says.@@ -36,6 +37,28 @@     -- * Checking a filter against a profile     FilterProfileError (..),     checkFiltersAgainstProfile,++    -- * Where conditions+    WhereCondition (..),+    ConceptPredicate (..),+    WhereParseError (..),+    parseWhereCondition,+    renderWhereCondition,+    renderConceptPredicate,+    renderWhereParseError,+    matchesPredicate,+    filterConceptsWhere,+    checkPredicateAgainstProfile,++    -- * Sorting concepts+    SortDirection (..),+    SortKey (..),+    SortKeyParseError (..),+    parseSortKey,+    renderSortKey,+    renderSortKeyParseError,+    compareNatural,+    sortConcepts,   ) where @@ -43,9 +66,13 @@ import Data.Aeson.Key qualified as AesonKey import Data.Aeson.KeyMap qualified as KeyMap import Data.ByteString.Lazy qualified as LazyByteString+import Data.Char (isAsciiLower, isAsciiUpper, isDigit, isSpace) import Data.List qualified as List+import Data.List.NonEmpty qualified as NonEmpty import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map+import Data.Maybe (mapMaybe)+import Data.Scientific (Scientific) import Data.Set qualified as Set import Data.Text qualified as Text import Data.Text.Encoding qualified as Text.Encoding@@ -53,6 +80,7 @@ import Okf.Bundle (Concept, conceptDocument) import Okf.Document (OKFDocument (frontmatter), coreFrontmatterFields, frontmatterLookup) import Okf.Prelude+ -- Imported with an explicit list that leaves out the 'Cardinality' -- constructors: two of them are named 'List' and 'Object', which would clash -- with aeson's 'Value' constructors of the same names.@@ -397,3 +425,692 @@      profileSpec :: ProfileSpec     profileSpec = compiledProfileSpec compiled++-- | One @--where@ argument, as the user wrote it.+--+-- The two constructors keep apart two readings that must never mix. A+-- 'LegacyWhere' equality joins 'filterConcepts' grouping, where repeating a+-- key means \"either\" — @--where status=accepted --where status=proposed@ has+-- selected both for as long as the flag has existed, and scripts depend on it.+-- A 'PredicateWhere' is an explicit condition and stands on its own: repeating+-- one means \"and\", and an @and@ written inside one means \"and\" even when+-- both sides name the same key. Flattening a predicate's equalities into the+-- legacy groups would quietly turn @(status=\"accepted\" and+-- status=\"proposed\")@ into an \"or\".+data WhereCondition+  = LegacyWhere !ConceptFilter+  | PredicateWhere !ConceptPredicate+  deriving stock (Generic, Eq, Ord, Show)++-- | A true-or-false question asked of one concept: atomic field questions+-- composed with @and@, @or@, and @not@.+data ConceptPredicate+  = -- | An existing atomic question: equality, presence, or absence.+    PredicateAtom !ConceptFilter+  | -- | The field holds at least one comparable scalar and none equals this.+    PredicateNotEquals !FieldSelector !Text+  | -- | Some comparable scalar of the field is one of these.+    PredicateIn !FieldSelector !(NonEmpty Text)+  | -- | The field holds at least one comparable scalar and none is one of+    -- these.+    PredicateNotIn !FieldSelector !(NonEmpty Text)+  | PredicateAnd !ConceptPredicate !ConceptPredicate+  | PredicateOr !ConceptPredicate !ConceptPredicate+  | -- | Ordinary boolean negation of the whole operand, absence included:+    -- @not (status=\"completed\")@ selects a concept with no @status@.+    PredicateNot !ConceptPredicate+  deriving stock (Generic, Eq, Ord, Show)++-- | Why a @--where@ argument could not be read.+data WhereParseError+  = -- | A @KEY=VALUE@ argument failed exactly as it always has.+    LegacyWhereParseError !FilterParseError+  | -- | New syntax went wrong: the original input, the zero-based character+    -- offset where reading stopped, and what was expected there.+    InvalidWhereSyntax !Text !Int !Text+  deriving stock (Generic, Eq, Show)++-- | Read one @--where@ argument.+--+-- Which grammar applies is decided up front from the argument's first+-- characters, never by trying one grammar and falling back to another:+--+-- * An argument whose first non-whitespace character is @(@ is one fully+--   parenthesized expression, with JSON-quoted strings.+-- * An argument that starts with @FIELD!=@, @FIELD in@, or @FIELD not in@ is a+--   standalone inequality or set condition. Once that prefix is seen, a+--   malformed operand is an error; it is not reread as an equality.+-- * Everything else goes to 'parseFieldEquals' untouched.+--+-- The dispatch is this narrow because legacy equality values are verbatim and+-- may hold anything — another @=@, spaces, the word @and@ — and reinterpreting+-- @title=research and development@ as an expression would change what existing+-- scripts select. For the same reason a legacy argument is never trimmed.+parseWhereCondition :: Text -> Either WhereParseError WhereCondition+parseWhereCondition raw+  | "(" `Text.isPrefixOf` Text.stripStart raw =+      PredicateWhere <$> runWholeParser raw expressionArgumentParser+  | Just (selector, operator, cursor) <- standalonePrefix raw =+      PredicateWhere <$> standaloneOperand raw selector operator cursor+  | otherwise =+      first LegacyWhereParseError (LegacyWhere <$> parseFieldEquals raw)++-- | The condition in a form 'parseWhereCondition' reads back with the same+-- meaning. A standalone inequality or set is rendered standalone, so a+-- diagnostic quotes back what was typed; anything else is a parenthesized+-- expression.+renderWhereCondition :: WhereCondition -> Text+renderWhereCondition = \case+  LegacyWhere conceptFilter@(FieldEquals _ _) -> renderFilter conceptFilter+  LegacyWhere conceptFilter -> "(" <> renderConceptPredicate (PredicateAtom conceptFilter) <> ")"+  PredicateWhere (PredicateNotEquals selector value) ->+    renderFieldSelector selector <> "!=" <> value+  PredicateWhere predicate@(PredicateIn _ _) -> renderConceptPredicate predicate+  PredicateWhere predicate@(PredicateNotIn _ _) -> renderConceptPredicate predicate+  PredicateWhere predicate -> "(" <> renderConceptPredicate predicate <> ")"++-- | A predicate in expression syntax, without the outer parentheses an+-- expression argument needs. Parentheses appear only where precedence+-- requires them, plus around a negated compound so @not@ reads unambiguously.+renderConceptPredicate :: ConceptPredicate -> Text+renderConceptPredicate = renderAt 0+  where+    -- Precedence: or 1, and 2, not 3, atom 4. The right operand of a binary+    -- operator is rendered one level tighter so a right-nested tree keeps its+    -- shape when read back.+    renderAt :: Int -> ConceptPredicate -> Text+    renderAt context predicate+      | precedence predicate < context = "(" <> render predicate <> ")"+      | otherwise = render predicate++    precedence = \case+      PredicateOr _ _ -> 1+      PredicateAnd _ _ -> 2+      PredicateNot _ -> 3+      _ -> 4 :: Int++    render = \case+      PredicateAtom (FieldEquals selector value) -> key selector <> "=" <> jsonString value+      PredicateAtom (FieldPresent selector) -> "has(" <> key selector <> ")"+      PredicateAtom (FieldAbsent selector) -> "missing(" <> key selector <> ")"+      PredicateNotEquals selector value -> key selector <> "!=" <> jsonString value+      PredicateIn selector values -> key selector <> " in " <> jsonSet values+      PredicateNotIn selector values -> key selector <> " not in " <> jsonSet values+      PredicateAnd left right -> renderAt 2 left <> " and " <> renderAt 3 right+      PredicateOr left right -> renderAt 1 left <> " or " <> renderAt 2 right+      PredicateNot operand@(PredicateAtom (FieldPresent _)) -> "not " <> render operand+      PredicateNot operand@(PredicateAtom (FieldAbsent _)) -> "not " <> render operand+      PredicateNot operand@(PredicateNot _) -> "not " <> render operand+      PredicateNot operand -> "not (" <> render operand <> ")"++    key = renderFieldSelector+    jsonString = jsonText . String+    jsonSet = jsonText . Aeson.toJSON . NonEmpty.toList+    jsonText = Text.Encoding.decodeUtf8Lenient . LazyByteString.toStrict . Aeson.encode++renderWhereParseError :: WhereParseError -> Text+renderWhereParseError = \case+  LegacyWhereParseError parseError -> renderFilterParseError parseError+  InvalidWhereSyntax input offset expected ->+    "expected "+      <> expected+      <> " at offset "+      <> Text.pack (show offset)+      <> caret+    where+      -- A caret under the offending character, unless a newline in the input+      -- would make the column meaningless.+      caret+        | Text.any (== '\n') input = " in: " <> input+        | otherwise = "\n  " <> input <> "\n  " <> Text.replicate offset " " <> "^"++-- | Whether one concept satisfies one predicate.+--+-- Positive and negative value questions both need something to compare: a+-- comparable scalar is a string, number, or boolean, as 'scalarText' reads it,+-- whether it is the value itself or an element of a list. A concept with no+-- such scalar for the key — the key absent, null, an empty list, or only+-- records — fails @status!=completed@ just as it fails @status=completed@,+-- because \"its status is not completed\" is not something the concept says.+-- A negative question is __universal over a list__: @tags!=cli@ rejects a+-- concept tagged @[profiles, cli]@, because hiding a tag means hiding every+-- concept that carries it. Explicit @not@ is different: it is plain boolean+-- negation of its whole operand, absence included.+matchesPredicate :: ConceptPredicate -> Concept -> Bool+matchesPredicate predicate concept =+  case predicate of+    PredicateAtom conceptFilter -> matchesFilter conceptFilter concept+    PredicateNotEquals selector forbidden -> holdsNoneOf selector (== forbidden)+    PredicateIn selector wanted -> any (`elem` wanted) (comparable selector)+    PredicateNotIn selector forbidden -> holdsNoneOf selector (`elem` forbidden)+    PredicateAnd left right -> matchesPredicate left concept && matchesPredicate right concept+    PredicateOr left right -> matchesPredicate left concept || matchesPredicate right concept+    PredicateNot operand -> not (matchesPredicate operand concept)+  where+    comparable selector = mapMaybe scalarText (conceptFieldValues selector concept)+    holdsNoneOf selector isForbidden =+      case comparable selector of+        [] -> False+        values -> not (any isForbidden values)++-- | Keep the concepts that satisfy the given legacy filters together with+-- every condition, in the order they arrived.+--+-- Legacy equalities join the supplied filters and are answered by+-- 'filterConcepts', so repeating a legacy key still means \"either\". Every+-- predicate must then hold on its own: repeating one is an \"and\", even on the+-- same key, so two @--where status!=...@ flags exclude both values.+filterConceptsWhere :: [ConceptFilter] -> [WhereCondition] -> [Concept] -> [Concept]+filterConceptsWhere filters conditions concepts =+  filter satisfiesPredicates (filterConcepts (filters <> legacyFilters) concepts)+  where+    legacyFilters = [conceptFilter | LegacyWhere conceptFilter <- conditions]+    predicates = [predicate | PredicateWhere predicate <- conditions]+    satisfiesPredicates concept = all (`matchesPredicate` concept) predicates++-- | Check every field and value a predicate mentions against a profile, as+-- 'checkFiltersAgainstProfile' checks a legacy filter.+--+-- Every operand counts, including those under @not@ and on either side of+-- @or@: a misspelled exclusion is otherwise silently ineffective, which is+-- worse than a misspelled inclusion because the listing still looks right.+-- Each excluded value or set member is checked as the equality it names, so+-- scopes, nested vocabularies, the core-key fallback, and @type@ checking are+-- exactly the legacy ones. Requested types come from the caller; a @type@+-- equality inside an expression does not narrow anything, and a contradiction+-- is not an error, only an empty result. Errors are reported once each, in the+-- order the predicate mentions them.+checkPredicateAgainstProfile :: CompiledProfile -> [Text] -> ConceptPredicate -> [FilterProfileError]+checkPredicateAgainstProfile compiled requestedTypes =+  List.nub . checkFiltersAgainstProfile compiled requestedTypes . operandFilters+  where+    operandFilters = \case+      PredicateAtom conceptFilter -> [conceptFilter]+      PredicateNotEquals selector value -> [FieldEquals selector value]+      PredicateIn selector values -> FieldEquals selector <$> NonEmpty.toList values+      PredicateNotIn selector values -> FieldEquals selector <$> NonEmpty.toList values+      PredicateAnd left right -> operandFilters left <> operandFilters right+      PredicateOr left right -> operandFilters left <> operandFilters right+      PredicateNot operand -> operandFilters operand++-- Sorting ---------------------------------------------------------------------++-- | Which way one sort key orders concepts.+data SortDirection = Ascending | Descending+  deriving stock (Generic, Eq, Ord, Show)++-- | One @--sort@ argument: the frontmatter value to order by, and which way.+data SortKey = SortKey+  { sortSelector :: !FieldSelector,+    sortDirection :: !SortDirection+  }+  deriving stock (Generic, Eq, Show)++-- | Why a @--sort@ argument could not be read.+data SortKeyParseError+  = -- | The key itself was malformed, exactly as a filter key would be.+    SortKeySelectorError !FilterParseError+  | -- | A @:@ introduced something other than @asc@ or @desc@. Holds the whole+    -- argument and the offending suffix.+    InvalidSortDirection !Text !Text+  deriving stock (Generic, Eq, Show)++-- | Read @KEY@, @KEY:asc@, or @KEY:desc@.+--+-- Any @:@ introduces a direction, and the text after the last one must be+-- exactly @asc@ or @desc@. Reading @status:up@ as a key named @status:up@+-- would sort by nothing and look as though it had worked, so it is an error+-- instead; the cost is that a key containing a colon cannot be sorted on.+parseSortKey :: Text -> Either SortKeyParseError SortKey+parseSortKey raw =+  case Text.breakOnEnd ":" raw of+    ("", _) -> SortKey <$> selector raw <*> pure Ascending+    (beforeWithColon, suffix) -> do+      direction <- case suffix of+        "asc" -> Right Ascending+        "desc" -> Right Descending+        _ -> Left (InvalidSortDirection raw suffix)+      SortKey <$> selector (Text.dropEnd 1 beforeWithColon) <*> pure direction+  where+    selector = first SortKeySelectorError . parseFieldSelector++-- | The key in the form 'parseSortKey' reads back; ascending, the default, is+-- not spelled out.+renderSortKey :: SortKey -> Text+renderSortKey SortKey {sortSelector, sortDirection} =+  renderFieldSelector sortSelector <> case sortDirection of+    Ascending -> ""+    Descending -> ":desc"++renderSortKeyParseError :: SortKeyParseError -> Text+renderSortKeyParseError = \case+  SortKeySelectorError parseError -> renderFilterParseError parseError+  InvalidSortDirection raw suffix ->+    "sort direction must be asc or desc, not " <> suffix <> ", in " <> raw++-- | Compare two texts the way a person reads identifiers: @IR-2@ before+-- @IR-10@, @v0.9@ before @v0.13@.+--+-- Each text is split into runs of ASCII digits and runs of everything else.+-- Digit runs compare by numeric value, and on a tie the shorter spelling comes+-- first, so @IR-2@ precedes @IR-02@. Other runs compare by Unicode code point,+-- which keeps the order identical on every machine whatever its locale. A+-- digit run sorts before a text run, as an ASCII digit sorts before a letter.+-- Two texts whose runs are all equal fall back to plain comparison, so+-- distinct texts never compare equal and the order is total.+compareNatural :: Text -> Text -> Ordering+compareNatural left right =+  compare (naturalChunks left) (naturalChunks right) <> compare left right++-- | One run of a text under 'compareNatural'. The derived 'Ord' is the rule:+-- every 'DigitRun' before every 'TextRun', digit runs by value then length,+-- text runs by code point.+data NaturalChunk = DigitRun !Integer !Int | TextRun !Text+  deriving stock (Eq, Ord)++naturalChunks :: Text -> [NaturalChunk]+naturalChunks = map chunk . Text.groupBy (\a b -> isDigit a == isDigit b)+  where+    chunk run+      | Text.all isDigit run = DigitRun (read (Text.unpack run)) (Text.length run)+      | otherwise = TextRun run++-- | Text ordered by 'compareNatural'.+newtype NaturalText = NaturalText Text++instance Eq NaturalText where+  left == right = compare left right == EQ++instance Ord NaturalText where+  compare (NaturalText left) (NaturalText right) = compareNatural left right++-- | What a concept is sorted by for one key. Every number sorts before every+-- text value, which keeps the order total even for a key that mixes them.+data SortValue = SortNumber !Scientific | SortText !NaturalText+  deriving stock (Eq, Ord)++-- | A stored number compares numerically, because natural order on the text+-- @1.5@ and @1.25@ would get them backwards. Strings and booleans compare as+-- the text 'scalarText' gives them. A value with no scalar reading has no+-- sort value.+sortValue :: Value -> Maybe SortValue+sortValue = \case+  Number number -> Just (SortNumber number)+  value -> SortText . NaturalText <$> scalarText value++-- | Order concepts by frontmatter keys. The first key decides; later keys+-- break its ties.+--+-- Text compares in natural order ('compareNatural'), numbers numerically, and+-- every number before any text. A concept with no comparable value for a key+-- — the key absent, null, an empty list, or only records — sorts after every+-- concept that has one, in both directions: asking to sort by a key is asking+-- to see the concepts that carry it, and @:desc@ should not lead with those+-- that say nothing. A list sorts by its smallest value when ascending and its+-- largest when descending, so the order does not depend on how an author+-- happened to list the elements. Concepts equal on every key keep the order+-- they arrived in, which for a walked bundle is concept-ID order, so the+-- listing stays deterministic.+sortConcepts :: [SortKey] -> [Concept] -> [Concept]+sortConcepts [] concepts = concepts+sortConcepts keys concepts =+  map snd (List.sortBy (\(left, _) (right, _) -> mconcat (zipWith3 compareCell keys left right)) decorated)+  where+    -- Read each concept's values once per key rather than once per comparison.+    decorated = [(map (cellFor concept) keys, concept) | concept <- concepts]+    cellFor concept SortKey {sortSelector, sortDirection} =+      representative sortDirection (mapMaybe sortValue (conceptFieldValues sortSelector concept))+    representative _ [] = Nothing+    representative Ascending values = Just (minimum values)+    representative Descending values = Just (maximum values)+    compareCell SortKey {sortDirection} left right =+      case (left, right) of+        (Just x, Just y) -> case sortDirection of+          Ascending -> compare x y+          Descending -> compare y x+        (Just _, Nothing) -> LT+        (Nothing, Just _) -> GT+        (Nothing, Nothing) -> EQ++-- Reading ---------------------------------------------------------------------++-- | Where a parser stands: the zero-based character offset into the original+-- argument and the text still unread.+data Cursor = Cursor !Int !Text++-- | A small hand-written parser. It never backtracks across a committed+-- choice, so the offset it reports is where the input really went wrong.+newtype WhereParser value = WhereParser+  {runWhereParser :: Cursor -> Either (Int, Text) (value, Cursor)}++instance Functor WhereParser where+  fmap f (WhereParser run) = WhereParser (fmap (first f) . run)++instance Applicative WhereParser where+  pure value = WhereParser (\cursor -> Right (value, cursor))+  WhereParser runF <*> WhereParser runValue = WhereParser $ \cursor -> do+    (f, afterF) <- runF cursor+    (value, afterValue) <- runValue afterF+    pure (f value, afterValue)++instance Monad WhereParser where+  WhereParser run >>= continue = WhereParser $ \cursor -> do+    (value, next) <- run cursor+    runWhereParser (continue value) next++-- | Run a parser over a whole argument.+runWholeParser :: Text -> WhereParser value -> Either WhereParseError value+runWholeParser raw parser =+  case runWhereParser parser (Cursor 0 raw) of+    Left (offset, expected) -> Left (InvalidWhereSyntax raw offset expected)+    Right (value, _) -> Right value++remaining :: WhereParser Text+remaining = WhereParser (\cursor@(Cursor _ rest) -> Right (rest, cursor))++failHere :: Text -> WhereParser value+failHere expected = WhereParser (\(Cursor offset _) -> Left (offset, expected))++-- | Fail at an earlier offset, for an error best pointed at the start of the+-- construct rather than wherever scanning gave up.+failAt :: Int -> Text -> WhereParser value+failAt offset expected = WhereParser (\_ -> Left (offset, expected))++currentOffset :: WhereParser Int+currentOffset = WhereParser (\cursor@(Cursor offset _) -> Right (offset, cursor))++skipChars :: Int -> WhereParser ()+skipChars count =+  WhereParser (\(Cursor offset rest) -> Right ((), Cursor (offset + count) (Text.drop count rest)))++peekChar :: WhereParser (Maybe Char)+peekChar = fmap fst . Text.uncons <$> remaining++skipSpaces :: WhereParser ()+skipSpaces = do+  rest <- remaining+  skipChars (Text.length (Text.takeWhile isSpace rest))++expectChar :: Char -> Text -> WhereParser ()+expectChar wanted expected = do+  next <- peekChar+  if next == Just wanted then skipChars 1 else failHere expected++expectEnd :: Text -> WhereParser ()+expectEnd expected = do+  skipSpaces+  rest <- remaining+  unless (Text.null rest) (failHere expected)++-- | Consume a lowercase keyword if the input continues with it as a whole+-- word, so @orphan@ is never read as @or@.+keyword :: Text -> WhereParser Bool+keyword word = do+  rest <- remaining+  if word `Text.isPrefixOf` rest && wordBoundary (Text.drop (Text.length word) rest)+    then True <$ skipChars (Text.length word)+    else pure False++wordBoundary :: Text -> Bool+wordBoundary rest =+  case Text.uncons rest of+    Nothing -> True+    Just (next, _) -> not (isSegmentChar next || next == '.')++-- | A key segment starts with a letter or underscore and continues with+-- letters, digits, underscores, or hyphens.+isSegmentStart :: Char -> Bool+isSegmentStart c = isAsciiLower c || isAsciiUpper c || c == '_'++isSegmentChar :: Char -> Bool+isSegmentChar c = isSegmentStart c || isDigit c || c == '-'++segmentParser :: WhereParser Text+segmentParser = do+  rest <- remaining+  case Text.uncons rest of+    Just (next, _)+      | isSegmentStart next -> do+          let segment = Text.takeWhile isSegmentChar rest+          segment <$ skipChars (Text.length segment)+    _ -> failHere "a frontmatter key such as status or reviews.outcome"++-- | @KEY@ or @PARENT.MEMBER@, with the same one-level limit as+-- 'parseFieldSelector' and for the same reason.+selectorParser :: WhereParser FieldSelector+selectorParser = do+  parentKey <- segmentParser+  next <- peekChar+  if next /= Just '.'+    then pure (TopLevelField parentKey)+    else do+      skipChars 1+      memberKey <- segmentParser+      deeper <- peekChar+      when (deeper == Just '.') $+        failHere "an operator; a frontmatter key nests at most one level (KEY or PARENT.MEMBER)"+      pure (NestedField parentKey memberKey)++-- | A JSON double-quoted string, decoded by aeson so escapes mean exactly what+-- they mean in JSON. The scan only finds where the string ends.+jsonStringParser :: Text -> WhereParser Text+jsonStringParser expected = do+  start <- currentOffset+  rest <- remaining+  case Text.uncons rest of+    Just ('"', body) ->+      case closingQuote 1 body of+        Nothing -> failAt start "a closing quotation mark for the string that starts here"+        Just width ->+          case Aeson.eitherDecodeStrict (Text.Encoding.encodeUtf8 (Text.take width rest)) of+            Left _ -> failAt start "a valid JSON string; check its escape sequences"+            Right decoded -> decoded <$ skipChars width+    _ -> failHere expected+  where+    -- The width of the whole string literal, quotes included.+    closingQuote :: Int -> Text -> Maybe Int+    closingQuote consumed body =+      case Text.uncons body of+        Nothing -> Nothing+        Just ('"', _) -> Just (consumed + 1)+        Just ('\\', escaped) ->+          if Text.null escaped then Nothing else closingQuote (consumed + 2) (Text.drop 1 escaped)+        Just (_, next) -> closingQuote (consumed + 1) next++-- | A non-empty JSON array of strings. Duplicates are dropped, keeping the+-- first occurrence, since a set mentioning a value twice means the same as+-- mentioning it once.+jsonStringSetParser :: WhereParser (NonEmpty Text)+jsonStringSetParser = do+  expectChar '[' "a non-empty JSON array of strings such as [\"accepted\",\"proposed\"]"+  skipSpaces+  next <- peekChar+  when (next == Just ']') $+    failHere "at least one string in the set; an empty set can never match"+  firstMember <- member+  NonEmpty.nub . (firstMember :|) <$> moreMembers+  where+    member = jsonStringParser "a JSON double-quoted string as a set member"+    moreMembers = do+      skipSpaces+      next <- peekChar+      case next of+        Just ',' -> do+          skipChars 1+          skipSpaces+          value <- member+          (value :) <$> moreMembers+        Just ']' -> [] <$ skipChars 1+        _ -> failHere "a comma or a closing bracket to continue the set"++-- | The standalone operators recognized after a leading field.+data StandaloneOperator+  = StandaloneNotEquals+  | StandaloneIn+  | StandaloneNotIn++-- | Recognize @FIELD!=@, @FIELD in@, or @FIELD not in@ at the very start of an+-- argument, without judging what follows. A keyword here must be followed by+-- whitespace, @[@, or the end, which is stricter than inside an expression so+-- that fewer legacy keys can ever be mistaken for one.+standalonePrefix :: Text -> Maybe (FieldSelector, StandaloneOperator, Cursor)+standalonePrefix raw = do+  (selector, Cursor offset rest) <- either (const Nothing) Just (runWhereParser selectorParser (Cursor 0 raw))+  let (spaces, afterSpaces) = Text.span isSpace rest+      afterSpacesOffset = offset + Text.length spaces+  if+    | "!=" `Text.isPrefixOf` rest ->+        Just (selector, StandaloneNotEquals, Cursor (offset + 2) (Text.drop 2 rest))+    | Text.null spaces -> Nothing+    | Just afterIn <- standaloneKeyword "in" afterSpaces ->+        Just (selector, StandaloneIn, Cursor (afterSpacesOffset + 2) afterIn)+    | Just afterNot <- standaloneKeyword "not" afterSpaces,+      (notSpaces, afterNotSpaces) <- Text.span isSpace afterNot,+      not (Text.null notSpaces),+      Just afterIn <- standaloneKeyword "in" afterNotSpaces ->+        Just+          ( selector,+            StandaloneNotIn,+            Cursor (afterSpacesOffset + 3 + Text.length notSpaces + 2) afterIn+          )+    | otherwise -> Nothing+  where+    standaloneKeyword word text = do+      afterWord <- Text.stripPrefix word text+      case Text.uncons afterWord of+        Nothing -> Just afterWord+        Just (next, _)+          | isSpace next || next == '[' -> Just afterWord+          | otherwise -> Nothing++-- | The operand of a recognized standalone operator. An inequality's value is+-- the rest of the argument verbatim, exactly like a legacy equality's; a set+-- is JSON and must be all that is left.+standaloneOperand :: Text -> FieldSelector -> StandaloneOperator -> Cursor -> Either WhereParseError ConceptPredicate+standaloneOperand raw selector operator cursor@(Cursor _ rest) =+  case operator of+    StandaloneNotEquals -> Right (PredicateNotEquals selector rest)+    StandaloneIn -> PredicateIn selector <$> setOperand+    StandaloneNotIn -> PredicateNotIn selector <$> setOperand+  where+    setOperand =+      case runWhereParser (skipSpaces *> jsonStringSetParser <* expectEnd "the end of the condition after the set") cursor of+        Left (offset, expected) -> Left (InvalidWhereSyntax raw offset expected)+        Right (values, _) -> Right values++-- | @( expression )@, followed by nothing but whitespace.+expressionArgumentParser :: WhereParser ConceptPredicate+expressionArgumentParser = do+  skipSpaces+  expectChar '(' "an opening parenthesis"+  predicate <- expressionParser+  skipSpaces+  expectChar ')' "and, or, or a closing parenthesis"+  expectEnd "the end of the condition after its closing parenthesis; wrap the whole condition in one pair of parentheses"+  pure predicate++-- | @or@ binds loosest, then @and@, then @not@; both binary operators group+-- to the left.+expressionParser :: WhereParser ConceptPredicate+expressionParser = conjunctionParser >>= alternatives+  where+    alternatives left = do+      skipSpaces+      isOr <- keyword "or"+      if isOr+        then conjunctionParser >>= alternatives . PredicateOr left+        else pure left++conjunctionParser :: WhereParser ConceptPredicate+conjunctionParser = unaryParser >>= conjunctions+  where+    conjunctions left = do+      skipSpaces+      isAnd <- keyword "and"+      if isAnd+        then unaryParser >>= conjunctions . PredicateAnd left+        else pure left++unaryParser :: WhereParser ConceptPredicate+unaryParser = do+  skipSpaces+  next <- peekChar+  case next of+    Just '(' -> do+      skipChars 1+      predicate <- expressionParser+      skipSpaces+      expectChar ')' "and, or, or a closing parenthesis"+      pure predicate+    _ -> do+      isNot <- negationKeyword+      if isNot then PredicateNot <$> unaryParser else atomParser++-- | @not@ as an operator, unless it is plainly a key named @not@ being+-- compared: @(not="x")@.+negationKeyword :: WhereParser Bool+negationKeyword = do+  rest <- remaining+  case Text.stripPrefix "not" rest of+    Just afterNot+      | wordBoundary afterNot,+        not (any (`Text.isPrefixOf` Text.stripStart afterNot) ["=", "!="]) ->+          True <$ skipChars 3+    _ -> pure False++atomParser :: WhereParser ConceptPredicate+atomParser = do+  rest <- remaining+  case Text.uncons rest of+    Just (next, _) | isSegmentStart next -> pure ()+    _ ->+      failHere+        "a condition: KEY=\"VALUE\", KEY!=\"VALUE\", KEY in [...], KEY not in [...], has(KEY), missing(KEY), not CONDITION, or a parenthesized condition"+  if+    | isFunctionCall "has" rest -> PredicateAtom . FieldPresent <$> functionCall "has"+    | isFunctionCall "missing" rest -> PredicateAtom . FieldAbsent <$> functionCall "missing"+    | otherwise -> do+        selector <- selectorParser+        skipSpaces+        operatorParser selector+  where+    isFunctionCall name text =+      case Text.stripPrefix name text of+        Just afterName -> "(" `Text.isPrefixOf` Text.stripStart afterName+        Nothing -> False+    functionCall name = do+      skipChars (Text.length name)+      skipSpaces+      expectChar '(' "an opening parenthesis"+      skipSpaces+      selector <- selectorParser+      skipSpaces+      expectChar ')' "a closing parenthesis after the key"+      pure selector++operatorParser :: FieldSelector -> WhereParser ConceptPredicate+operatorParser selector = do+  rest <- remaining+  if+    | "!=" `Text.isPrefixOf` rest -> do+        skipChars 2+        skipSpaces+        PredicateNotEquals selector <$> stringOperand+    | "=" `Text.isPrefixOf` rest -> do+        skipChars 1+        skipSpaces+        PredicateAtom . FieldEquals selector <$> stringOperand+    | otherwise -> do+        isIn <- keyword "in"+        if isIn+          then skipSpaces *> (PredicateIn selector <$> jsonStringSetParser)+          else do+            isNot <- keyword "not"+            unless isNot (failHere "an operator: =, !=, in, or not in")+            skipSpaces+            isNotIn <- keyword "in"+            unless isNotIn (failHere "in after not")+            skipSpaces+            PredicateNotIn selector <$> jsonStringSetParser+  where+    stringOperand = jsonStringParser "a JSON double-quoted string such as \"accepted\""
test/Main.hs view
@@ -2,7437 +2,9090 @@  module Main (main) where -import Data.Aeson (object, toJSON, (.=))-import Data.Aeson qualified as Aeson-import Data.Aeson.KeyMap qualified as KeyMap-import Data.Foldable (for_, toList)-import Data.List qualified as List-import Data.Map.Strict (Map)-import Data.Map.Strict qualified as Map-import Data.Maybe (catMaybes, maybeToList)-import Data.Set qualified as Set-import Data.Text qualified as Text-import Data.Text.IO qualified as Text.IO-import Data.Time (fromGregorian)-import Okf.Actor-import Okf.Bundle-import Okf.ConceptId-import Okf.Discovery-import Okf.Document-import Okf.Graph-import Okf.Index-import Okf.Log-import Okf.Markdown-import Okf.Path--- 'List' and 'Object' are 'Cardinality' constructors; aeson's same-named--- 'Value' constructors are reached as 'Aeson.Object' and friends.-import Okf.Prelude hiding (List, Object, setField, (.=))--- 'HumanActor' is both an 'Okf.Actor' constructor and a 'FieldFormat'--- alternative. This module names the actor far more often, so the format is--- reached as 'Profile.HumanActor'.-import Okf.Profile hiding (HumanActor)-import Okf.Profile qualified as Profile-import Okf.Profile.Discovery qualified as ProfileDiscovery-import Okf.Profile.Documentation-import Okf.Profile.Registry-import Okf.Query-import Okf.Trust-import Okf.Validation-import System.Directory-  ( createDirectoryIfMissing,-    createFileLink,-    doesDirectoryExist,-    doesFileExist,-    getTemporaryDirectory,-    makeAbsolute,-    removeDirectoryRecursive,-  )-import System.Exit (exitFailure)-import System.FilePath (normalise, takeDirectory, (</>))-import System.IO.Temp (createTempDirectory)-import "generic-lens" Data.Generics.Labels ()--main :: IO ()-main = do-  results <--    sequence-      [ test "parseActor classifies the three specification section 7 shapes" testParseActorShapes,-        test "renderActor inverts parseActor on every input" testActorRoundTrip,-        test "parse valid document with YAML frontmatter" testParseValidDocument,-        test "parse document with no frontmatter as empty-frontmatter body" testParseNoFrontmatter,-        test "reject unterminated frontmatter" testRejectUnterminatedFrontmatter,-        test "reject frontmatter that is not a YAML mapping" testRejectNonMappingFrontmatter,-        test "validate permissive profile with only type" testPermissiveValidation,-        test "validate strict profile requiring title description generated" testStrictValidation,-        test "strict validation accepts generated, falls back to timestamp, reports neither" testStrictValidationGeneratedFamily,-        test "validate rejects tags that are not a string list" testRejectInvalidTags,-        test "round-trip preserves semantic frontmatter and body" testRoundTrip,-        test "reject invalid concept id segment" testRejectInvalidConceptId,-        test "convert concept id tables/users to tables/users.md" testConceptIdToFilePath,-        testIO "walkBundle reports a structured IO error for a missing root" testWalkBundleMissingRoot,-        testIO "walkBundle skips index.md and log.md" testWalkBundleSkipsReserved,-        testIO "walkBundle discovers nested concept IDs" testWalkBundleDiscoversNestedConceptIds,-        testIO "walkBundleInventory sees a non-Markdown file that is not a concept" testWalkBundleInventorySeesNonMarkdown,-        testIO "discoverBundleRoots finds a directory holding index.md" testDiscoverIndexMd,-        testIO "discoverBundleRoots finds a directory holding a typed concept" testDiscoverTypedConcept,-        testIO "discoverBundleRoots ignores markdown without a type field" testDiscoverIgnoresPlainMarkdown,-        testIO "discoverBundleRoots does not descend into a bundle it found" testDiscoverPrunesNestedBundles,-        testIO "discoverBundleRoots skips hidden and build directories" testDiscoverSkipsNoise,-        testIO "discoverBundleRoots honours maxDepth" testDiscoverHonoursMaxDepth,-        testIO "discoverBundleRoots reports a fixture bundle as its own root" testDiscoverFixtureBundle,-        test "parseLog/serializeLog round-trips a canonical log" testLogRoundTrip,-        test "validateLog flags a non-ISO date heading" testValidateLogNonIsoDate,-        test "validateLog flags an empty date group" testValidateLogEmptyDay,-        test "validateLog flags out-of-order days" testValidateLogOutOfOrder,-        testIO "walkLogs discovers nested log.md files" testWalkLogsDiscoversNested,-        test "logStaleness flags a concept newer than its nearest log" testLogStalenessFlagsNewerConcept,-        test "logStaleness reads generated.at ahead of the legacy timestamp" testLogStalenessReadsGeneratedAt,-        test "logStaleness prefers the deepest enclosing log" testLogStalenessPrefersDeepestLog,-        test "appendLogEntry inserts newest-first and prepends within a day" testAppendLogEntry,-        testIO "generateIndex groups documents by frontmatter type" testGenerateIndexGroupsByType,-        testIO "extractLinks resolves relative and absolute bundle links" testExtractLinksResolveBundleLinks,-        testIO "extractLinks ignores external markdown URLs" testExtractLinksIgnoresExternalUrls,-        testIO "buildGraph includes only edges to existing concepts" testBuildGraphIncludesKnownEdges,-        testIO "writeBundleIndexes is deterministic" testWriteBundleIndexesDeterministic,-        testIO "readBundleVersion reads a declared, absent, or unparseable okf_version" testReadBundleVersion,-        testIO "readBundleVersion accepts the unquoted YAML number form" testReadBundleVersionUnquoted,-        testIO "writeBundleIndexes preserves an existing okf_version declaration" testWriteBundleIndexesPreservesVersion,-        testIO "writeBundleIndexesWith declares a version and leaves others alone" testWriteBundleIndexesDeclaresVersion,-        testIO "fixture valid bundle validates and graphs expected edges" testFixtureValidBundle,-        testIO "fixture v01 legacy bundle validates strictly through the fallback" testFixtureV01LegacyBundle,-        testIO "fixture graph JSON shape is stable" testFixtureGraphJsonShape,-        testIO "fixture unterminated frontmatter reports parse error" testFixtureUnterminatedFrontmatter,-        testIO "fixture missing type reports validation error" testFixtureMissingType,-        test "frontmatter builder round-trips through serialize and parse" testFrontmatterBuilderRoundTrip,-        test "serializeDocument emits deterministic key order" testSerializeDeterministicKeyOrder,-        test "serializeDocument orders generated before the superseded timestamp" testSerializeGeneratedBeforeTimestamp,-        test "strict validation joins footnote labels to sources ids in both directions" testFootnoteAttributionJoin,-        test "footnote attribution is skipped entirely when a document has no sources" testFootnoteAttributionSkippedWithoutSources,-        test "footnote parsing is enabled, so a definition is not paragraph text" testFootnotesEnabled,-        test "enabling footnotes leaves log parsing and link extraction unchanged" testFootnotesDoNotRegressLogsOrLinks,-        test "extractFootnoteLabels ignores footnote syntax inside code" testExtractFootnoteLabelsIgnoresCode,-        test "extractFootnoteLabels keeps labels the parser erases and never ordinals" testExtractFootnoteLabelsKeepsErasedLabels,-        test "computationBlocks accepts both spellings and bounds its section" testComputationBlocks,-        test "computationBlocks cannot see a block inside an uncited footnote definition" testComputationBlocksFootnoteHazard,-        test "rendered concept link round-trips through extractConceptLinks" testConceptLinkRoundTrip,-        test "over-escaping relative links do not resolve inside bundle" testRejectOverEscapingRelativeLink,-        test "classifyPathReference implements the specification section 6.2 grammar" testClassifyPathReference,-        test "resolvePathReference decides existence against a bundle inventory" testResolvePathReference,-        test "every versioned field name is a core frontmatter field" testVersionedFieldsAreCoreFields,-        test "versionGate applies specification section 12 best-effort reading" testVersionGate,-        test "declared v0.2 reports a legacy timestamp that an undeclared bundle tolerates" testLegacyFieldInDeclaredV2,-        test "an unreadable or unknown declaration is a strict lint, never a refusal" testVersionDeclarationLints,-        test "validateBundle reports a dangling reference" testValidateBundleDanglingReference,-        test "validateBundle accepts a bundle whose links all resolve" testValidateBundleAcceptsResolved,-        test "validateBundle reports a dangling frontmatter path under strict only" testValidateBundleDanglingFrontmatterPath,-        test "a dangling relative path names the bundle-relative spelling that resolves" testDanglingFrontmatterPathAlternative,-        test "duplicateConceptIds finds repeated ids" testDuplicateConceptIds,-        test "conceptFromDocument derives typed fields from frontmatter" testConceptFromDocumentDerivesFields,-        test "conceptGenerated projects the v0.2 generated family" testConceptGeneratedProjection,-        test "readGenerated ignores a generated mapping with no by actor" testReadGeneratedWithoutActor,-        test "readVerified reads a list and normalises a bare mapping to one element" testReadVerifiedShapes,-        test "setVerified always writes a list and round-trips" testVerifiedRoundTrip,-        test "readStatus defaults to stable and preserves an unknown value" testReadStatus,-        test "readStaleAfter reads the date verbatim" testReadStaleAfter,-        test "trustTier derives the three specification section 5.3 tiers" testTrustTier,-        test "latestVerification returns the newest at" testLatestVerification,-        test "staleness compares inclusively against a supplied day" testStaleness,-        test "readSources reads entries and skips one without resource" testReadSources,-        test "usage_window applies at document scope with per-entry override" testUsageWindowOverride,-        test "setSources and setUsageWindow round-trip through serialize and parse" testSourcesRoundTrip,-        test "strict validation reports sources missing resource and duplicate ids" testValidateSources,-        test "the attested computation contract reads from the specification worked example" testReadAttestedComputationContract,-        test "a malformed contract field is not read rather than rejected" testReadAttestedComputationDegenerateShapes,-        test "the specification worked example serializes byte-identically" testAttestedComputationRoundTrip,-        test "readComputationSources joins the body section to the computation key" testReadComputationSources,-        test "strict validation reports an Attested Computation with no runtime" testValidateAttestedComputationRuntime,-        testIO "writeBundle then walkBundle round-trips" testWriteBundleRoundTrip,-        testIO "fixture dangling link reports a bundle validation error" testFixtureDanglingLink,-        testIO "fixture dangling frontmatter path reports exactly one strict problem" testFixtureDanglingFrontmatterPath,-        testIO "fixture attested computation bundle reports one missing runtime and no path problem" testFixtureAttestedComputation,-        testIO "loadProfileFile decodes the postgresql fixture" testLoadProfileFixture,-        testIO "loadProfileFile decodes record-completed document ID rules" testLoadDocumentIdProfileFixture,-        testIO "loadProfileFile exposes nested reference and uniqueness declarations" testLoadNestedReferenceProfileFixture,-        testIO "loadProfileFile accepts the pre-type-frontmatter described schema" testLoadDescribedProfileFixture,-        testIO "loadProfileFile accepts the frozen EP-1 type-aware schema" testLoadTypeAwareCompatibilityFixture,-        testIO "loadProfileFile accepts the frozen EP-2 vocabulary schema" testLoadVocabularyCompatibilityFixture,-        testIO "loadProfileFile accepts the frozen EP-3 cardinality schema" testLoadCardinalityCompatibilityFixture,-        testIO "loadProfileFile accepts the frozen EP-4 format schema" testLoadFormatCompatibilityFixture,-        testIO "loadProfileFile decodes bounded nested review rules" testLoadNestedReviewsProfileFixture,-        testIO "loadProfileFile preserves the frozen bounded-nested schema" testLoadNestedCompatibilityFixture,-        testIO "loadProfileFile decodes same-scope conditions" testLoadConditionalFieldsProfileFixture,-        testIO "loadProfileFile preserves the frozen condition-aware schema" testLoadConditionalCompatibilityFixture,-        testIO "loadProfileFile preserves the frozen reference-aware schema" testLoadReferenceCompatibilityFixture,-        testIO "loadProfileFile preserves the complete 0.7.0.0 descriptor schema" testLoadPreNestedReferenceCompatibilityFixture,-        testIO "loadProfileFile and registry decoding preserve the complete 0.8.0.0 descriptor schema" testLoadPreGuidanceCompatibilityFixture,-        testIO "loadProfileFile and JSON preserve multiline guidance" testLoadGuidanceFixture,-        testIO "guidance does not affect profile validation" testGuidanceDoesNotAffectValidation,-        testIO "every frozen generation fixture compiles, not merely decodes" testFrozenFixturesCompile,-        testIO "loadProfileFile preserves the frozen pre-bundle-version schema" testLoadPreBundleVersionCompatibilityFixture,-        testIO "loadProfileFile preserves the frozen pre-path schema" testLoadPrePathCompatibilityFixture,-        testIO "loadProfileFile preserves the frozen five-alternative format union" testLoadPreActorCompatibilityFixture,-        testIO "loadProfileFile preserves the frozen optional-presence schema" testLoadPreObjectCompatibilityFixture,-        testIO "loadProfileFile still accepts an okf 0.2.x descriptor" testLoadLegacyProfileFixture,-        testIO "profileFieldDescription finds required and recommended prose" testProfileFieldDescription,-        testIO "profileFieldDescription finds optional prose" testOptionalFieldDescription,-        testIO "profile JSON encoding emits type, not type_" testProfileJsonShape,-        test "field condition JSON encoding is stable" testFieldConditionJsonShape,-        test "handle reference JSON encoding is stable" testHandleReferenceJsonShape,-        test "field format JSON encoding is stable" testFieldFormatJsonShape,-        testIO "loadRegistry enumerates nested profiles and skips non-profiles" testRegistryEnumeratesProfiles,-        testIO "loadRegistry decodes every profile in the pinned catalogue snapshot" testPinnedCatalogueDecodes,-        testIO "loadRegistry reports a bare profile as a root entry" testRegistryRootProfile,-        testIO "resolveRegistryRef prefers package.dhall inside a directory" testResolveRegistryRef,-        testIO "loadRegistry reports a missing registry as Left" testRegistryLoadFailure,-        test "registry path intent is classified without mistaking remote URLs for paths" testLooksLikeRegistryPath,-        testIO "loadRegistryDetailed classifies actionable failures without rendered Dhall text" testRegistryDetailedFailures,-        testIO "profile discovery finds valid descriptors without pruning" testDiscoverProfileDescriptors,-        testIO "profile discovery excludes every non-descriptor fixture" testProfileDescriptorQualification,-        testIO "profile discovery treats a missing root as empty" testProfileDiscoveryMissingRoot,-        testIO "profile discovery skips symbolic links" testProfileDiscoverySkipsSymlink,-        testIO "profile discovery honours maxDepth" testProfileDiscoveryHonoursMaxDepth,-        testIO "profile discovery rejects remote text and bytes before I/O" testProfileDiscoveryRejectsRemote,-        test "profile source labels are compact and readable" testProfileSourceLabels,-        testIO "loadProfileSource attaches source provenance" testProfileSourceWrapper,-        testIO "DescriptorSource enumerates one basename export" testDescriptorSourceWrapper,-        testIO "DescriptorSource reports a non-profile as a source failure" testDescriptorSourceFailure,-        testIO "loadProfileSources merges registries in source order" testProfileSourcesMergeInOrder,-        testIO "loadProfileSources merges registry and descriptor sources in order" testMixedProfileSourcesMergeInOrder,-        testIO "loadProfileSources retains entries after a partial failure" testProfileSourcesPartialFailure,-        testIO "findSourcedProfiles exposes cross-source collisions" testProfileSourcesExposeCollisions,-        testIO "loadProfileSources drops exact duplicate references" testProfileSourcesDropDuplicates,-        test "parseDocumentId accepts only canonical handles" testParseDocumentId,-        testIO "documentIdsInBundle sorts handles by prefix and number" testDocumentIdsInBundle,-        test "nextDocumentId skips gaps and starts unused prefixes at one" testNextDocumentId,-        testIO "findConceptsByDocumentId resolves and reports duplicate handles" testFindConceptsByDocumentId,-        test "compileProfile rejects ambiguous definitions deterministically" testCompileProfileDefinitionErrors,-        test "compiled rules merge profile and type requirements" testCompiledProfileMerge,-        testIO "compiledProfileTypeNames preserves declaration order" testCompiledProfileTypeNames,-        testIO "compiledProfileRulesForType merges profile and type scope" testCompiledProfileRulesMergeTypeScope,-        testIO "compiled optional rules carry no presence clause" testCompiledProfileOptionalPresence,-        test "profileDocumentationSlug normalizes free-text type names" testProfileDocumentationSlug,-        test "duplicate type slugs are disambiguated positionally" testProfileDocumentationSlugCollisions,-        test "profile value display names match the documented vocabulary" testProfileValueDisplayNames,-        testIO "profile documentation renders a root concept" testProfileDocumentationRootConcept,-        test "profile documentation renders object rules" testProfileDocumentationObjectFields,-        testIO "profile documentation renders nested references and list uniqueness" testProfileDocumentationNestedReferenceAndUniqueness,-        test "profile documentation renders a required bundle version" testProfileDocumentationRequiredBundleVersion,-        testIO "profile documentation renders one concept per declared type" testProfileDocumentationTypeConcept,-        testIO "profile documentation renders inherited rules for a bare type" testProfileDocumentationInheritedRules,-        testIO "profile documentation renders effective guidance without frontmatter leakage" testProfileDocumentationGuidance,-        testIO "generated profile documentation round-trips through serialize and parse" testProfileDocumentationRoundTrip,-        testIO "generated profile documentation validates permissively and strictly" testProfileDocumentationValidates,-        testIO "generated profile documentation carries the default generated actor" testProfileDocumentationDefaultGenerated,-        testIO "generated profile documentation honours an explicit generated family" testProfileDocumentationExplicitGenerated,-        testIO "generated profile documentation omits generated on request" testProfileDocumentationOmittedGenerated,-        testIO "generated profile documentation has no dangling references" testProfileDocumentationLinksResolve,-        testIO "generated profile documentation is byte-stable across renders" testProfileDocumentationByteStable,-        testIO "generated profile documentation survives a filesystem round trip" testProfileDocumentationFilesystemRoundTrip,-        test "compiled vocabularies intersect in profile declaration order" testCompiledVocabularyIntersection,-        test "compileProfile rejects disjoint vocabularies" testUnsatisfiableVocabulary,-        test "compiled cardinality uses Any as identity and rejects contradictions" testCompiledCardinality,-        test "profile vocabularies validate strings, lists, and shapes" testVocabularyValidation,-        test "profile cardinality validates all JSON shapes and presence" testCardinalityValidation,-        test "cardinality suppresses redundant vocabulary shape errors" testCardinalityVocabularyInteraction,-        test "compiled formats refine Uri and reject contradictions" testCompiledFieldFormats,-        test "compileProfile rejects invalid format parameters" testInvalidFormatParameters,-        test "named formats validate parser boundaries, lists, and shapes" testNamedFormatValidation,-        test "the actor formats accept the three specification section 7 shapes" testActorFormatValidation,-        test "the numeric and boolean formats reject text and non-integers" testNonTextualFormatValidation,-        test "a non-textual format refines an unspecified cardinality to scalar" testNonTextualFormatRefinesCardinality,-        test "actor and integer narrow across scopes" testNewFormatsNarrowAcrossScopes,-        test "compiled nested rules merge and reject impossible outer cardinality" testCompiledNestedRules,-        test "nested record validation reports indexed paths and strict recommendations" testNestedRecordValidation,-        test "compileProfile rejects objectFields with an explicit scalar or list cardinality" testObjectFieldsRequireObjectShape,-        test "compileProfile refines an object rule to object cardinality" testCompileObjectRule,-        test "compileProfile normalizes a path rule at top-level and nested scope" testCompilePathRule,-        test "a type-scope path rule narrows the profile-scope one" testMergePathRule,-        test "compileProfile rejects incoherent path rules" testPathDefinitionErrors,-        test "compileProfile rejects an unreadable or unknown-major okfVersion" testProfileVersionParsing,-        test "compileProfile clamps a higher okfVersion minor to the supported one" testProfileVersionMinorClamp,-        test "compileProfile rejects an unreadable requireBundleVersion" testRequiredBundleVersionParsing,-        test "validateProfileVersion judges every declaration shape" testValidateProfileVersion,-        test "validateProfileVersion is inert without a requirement" testValidateProfileVersionUnrequired,-        test "compileProfile rejects a superseded field outside the optional list" testProfileVersionSupersededField,-        test "compileProfile rejects the actor formats in a v0.1 profile" testProfileVersionActorFormat,-        test "compileProfile does not judge a profile by its key names" testProfileVersionDoesNotJudgeKeyNames,-        test "validateProfile checks a top-level path-valued field" testValidatePathTopLevel,-        test "validateProfile checks sources[].resource with element indexes" testValidatePathNested,-        test "validateProfile checks a path inside an object-valued field" testValidatePathObjectScope,-        testIO "validateProfileWith resolves a non-Markdown path target" testValidateProfileWithInventory,-        testIO "the documented house profile reports the section 10 contract deviations" testAttestedComputationHouseProfile,-        test "compileProfile keeps a rule declaring both shapes at any cardinality" testCompileRecordOrListRule,-        test "validateProfile requires a member of an object field" testValidateObjectMember,-        test "validateProfile checks a bare mapping and a list against the same member rules" testValidateRecordOrList,-        test "validateProfile reports an object value where only a list is declared" testValidateObjectWrongShape,-        test "an object field with no member rules still requires a mapping" testValidateEmptyObjectRules,-        test "compileProfile rejects invalid same-scope field conditions" testConditionDefinitionErrors,-        test "top-level conditions gate presence without gating value checks" testTopLevelConditionalPresence,-        test "nested conditions use siblings and avoid cascading diagnostics" testNestedConditionalPresence,-        test "compileProfile rejects invalid document reference policies" testReferenceDefinitionErrors,-        test "document references resolve local handles and explicit external URIs" testDocumentReferenceValidation,-        testIO "compileProfile exposes nested references and record-list uniqueness" testCompileNestedReferenceAndUniqueness,-        testIO "nested references and record-list uniqueness validate in layers" testNestedReferenceAndUniquenessValidation,-        testIO "compileProfile rejects invalid nested reference and uniqueness declarations" testNestedReferenceAndUniquenessDefinitionErrors,-        test "optional fields are never missing but are fully value-checked" testOptionalFieldPresence,-        test "optional reference fields resolve handles when present" testOptionalReferenceValidation,-        test "optional nested fields are never missing inside records" testOptionalNestedFieldPresence,-        test "optional fields count as declared under closed field names" testOptionalFieldClosure,-        test "optional at one scope does not cancel the other scope's clause" testOptionalDoesNotCancelOtherScope,-        test "compileProfile rejects optional collisions and dead conditions" testOptionalDefinitionErrors,-        test "closed profiles reject unknown fields and isolate type fields" testClosedFieldValidation,-        test "profile rules apply to unknown concept types" testProfileRulesApplyToUnknownTypes,-        test "strict profile validation checks recommendations" testStrictProfileRecommendations,-        test "validateProfile accepts a conforming table concept" testProfileConformingTable,-        test "validateProfile flags a type not in the vocabulary" testProfileUnknownType,-        test "validateProfile flags a missing required field" testProfileMissingField,-        test "validateProfile flags a resource scheme mismatch" testProfileResourceMismatch,-        test "validateProfile flags a path pattern mismatch" testProfilePathMismatch,-        test "validateProfile flags a missing # Schema section" testProfileMissingSchema,-        test "validateProfile flags mismatched # Schema columns" testProfileSchemaColumnsMismatch,-        test "validateProfile accepts a conforming document ID" testProfileConformingDocumentId,-        test "validateProfile flags a missing document ID" testProfileMissingDocumentId,-        test "validateProfile flags malformed document IDs" testProfileMalformedDocumentIds,-        test "validateProfile flags duplicate document IDs" testProfileDuplicateDocumentIds,-        test "validateProfile document ID checks are off by default" testProfileDocumentIdsOffByDefault,-        test "schemaSectionColumns reads the header row of the Schema table" testSchemaSectionColumns,-        testIO "validateProfile reports the expected deviations for the fixture bundle" testProfileDeviationsFixture,-        testIO "validateProfile reports document ID fixture deviations" testDocumentIdDeviationsFixture,-        testIO "type-aware fixture is permissive but reports one strict recommendation" testTypeAwareProfileFixture,-        testIO "closed-field fixture reports missing and misspelled fields" testClosedFieldsFixture,-        testIO "cardinality fixture reports scalar and list mismatches" testCardinalityFixture,-        testIO "format fixture reports parser-backed mismatches" testFormatsFixture,-        testIO "nested review fixture validates records with indexed diagnostics" testNestedReviewsFixture,-        testIO "conditional fixture covers ADR, PostgreSQL, and review scopes" testConditionalFieldsFixture,-        testIO "document reference fixture covers local, external, self, and duplicate targets" testDocumentReferencesFixture,-        testIO "optional-field fixture reports only the recommendation and bad values" testOptionalFieldsFixture,-        test "parseFieldEquals and parseFieldSelector read the filter grammar" testParseConceptFilters,-        test "scalarText compares numbers and booleans as JSON, containers as nothing" testQueryScalarText,-        testIO "filterConcepts selects over lists, nested records, presence, and absence" testFilterConceptsOverFixture,-        testIO "checkFiltersAgainstProfile rejects undeclared keys and out-of-vocabulary values" testCheckFiltersAgainstProfile-      ]-  unless (and results) exitFailure--test :: Text -> Either Text () -> IO Bool-test name assertion =-  case assertion of-    Right () -> do-      putStrLn ("PASS " <> Text.unpack name)-      pure True-    Left message -> do-      putStrLn ("FAIL " <> Text.unpack name <> ": " <> Text.unpack message)-      pure False--testIO :: Text -> IO (Either Text ()) -> IO Bool-testIO name assertion = do-  result <- assertion-  test name result--testParseActorShapes :: Either Text ()-testParseActorShapes = do-  assertEqual (HumanActor "ahormati") (parseActor "human:ahormati")-  assertEqual (ProcessActor "finance-nightly") (parseActor "process:finance-nightly")-  assertEqual (ProducerActor "reference_agent" "gemini-2.5-pro") (parseActor "reference_agent/gemini-2.5-pro")-  assertEqual (UnclassifiedActor "something") (parseActor "something")-  -- Section 7 writes the prefixes in lower case and section 5.3 makes the-  -- `human:` test load-bearing, so matching is case-sensitive.-  assertEqual (UnclassifiedActor "Human:ahormati") (parseActor "Human:ahormati")-  assertBool "human actor is human" (isHumanActor (parseActor "human:ahormati"))-  assertBool "producer actor is not human" (not (isHumanActor (parseActor "reference_agent/gemini-2.5-pro")))--testActorRoundTrip :: Either Text ()-testActorRoundTrip =-  for_-    [ "human:ahormati",-      "process:finance-nightly",-      "reference_agent/gemini-2.5-pro",-      "something",-      "Human:ahormati",-      "human:",-      "/version",-      "producer/",-      "a/b/c",-      ""-    ]-    (\raw -> assertEqual raw (renderActor (parseActor raw)))--testParseValidDocument :: Either Text ()-testParseValidDocument = do-  document <- firstShow (parseDocument sampleDocument)-  assertEqual (Just (String "BigQuery Table")) (frontmatterLookup "type" (document ^. #frontmatter))-  assertEqual "# Schema\n\nBody text.\n" (body document)--testParseNoFrontmatter :: Either Text ()-testParseNoFrontmatter = do-  document <- firstShow (parseDocument "# Draft\n")-  assertEqual Nothing (frontmatterLookup "type" (document ^. #frontmatter))-  assertEqual "# Draft\n" (body document)--testRejectUnterminatedFrontmatter :: Either Text ()-testRejectUnterminatedFrontmatter =-  assertEqual (Left UnterminatedFrontmatter) (parseDocument "---\ntype: BigQuery Table\n")--testRejectNonMappingFrontmatter :: Either Text ()-testRejectNonMappingFrontmatter =-  assertEqual (Left FrontmatterNotMapping) (parseDocument "---\n- one\n- two\n---\nBody\n")--testPermissiveValidation :: Either Text ()-testPermissiveValidation = do-  document <- firstShow (parseDocument "---\ntype: BigQuery Table\n---\nBody\n")-  assertEqual [] (validateDocument PermissiveConformance document)--testStrictValidation :: Either Text ()-testStrictValidation = do-  document <- firstShow (parseDocument "---\ntype: BigQuery Table\n---\nBody\n")-  let errors = validateDocument StrictAuthoring document-  assertBool "missing title" (MissingRecommendedField "title" `List.elem` errors)-  assertBool "missing description" (MissingRecommendedField "description" `List.elem` errors)-  assertBool "missing generated" (MissingGeneratedField `List.elem` errors)---- | Specification section 5.2 satisfies the "when was this last changed"--- requirement with `generated`, and section 13.1 permits falling back to the--- superseded v0.1 `timestamp`. Both must pass strict validation; neither--- present must fail it, naming the v0.2 field.-testStrictValidationGeneratedFamily :: Either Text ()-testStrictValidationGeneratedFamily = do-  let strictErrors source = validateDocument StrictAuthoring <$> firstShow (parseDocument source)-      preamble = "---\ntype: BigQuery Table\ntitle: Orders\ndescription: Order fact table.\n"-  withGenerated <- strictErrors (preamble <> "generated: { by: human:ahormati, at: 2026-06-20T22:53:05Z }\n---\nBody\n")-  assertEqual [] withGenerated-  withLegacyTimestamp <- strictErrors (preamble <> "timestamp: 2026-06-16T00:00:00Z\n---\nBody\n")-  assertEqual [] withLegacyTimestamp-  withNeither <- strictErrors (preamble <> "---\nBody\n")-  assertEqual [MissingGeneratedField] withNeither-  -- `generated` present but without the actor section 5.2 requires within it.-  withoutActor <- strictErrors (preamble <> "generated: { at: 2026-06-20T22:53:05Z }\n---\nBody\n")-  assertEqual [GeneratedMustHaveActor] withoutActor-  -- Section 11 forbids rejecting a bundle for a missing optional field, so-  -- neither diagnostic may fire under PermissiveConformance.-  permissive <- validateDocument PermissiveConformance <$> firstShow (parseDocument (preamble <> "---\nBody\n"))-  assertEqual [] permissive--testRejectInvalidTags :: Either Text ()-testRejectInvalidTags = do-  document <- firstShow (parseDocument "---\ntype: BigQuery Table\ntags: orders\n---\nBody\n")-  assertEqual [FieldMustBeListOfText "tags"] (validateDocument PermissiveConformance document)--testRoundTrip :: Either Text ()-testRoundTrip = do-  document <- firstShow (parseDocument sampleDocument)-  assertEqual [] (validateDocument PermissiveConformance document)-  assertEqual [] (validateDocument StrictAuthoring document)-  reparsed <- firstShow (parseDocument (serializeDocument document))-  assertEqual (document ^. #frontmatter) (reparsed ^. #frontmatter)-  assertEqual (body document) (body reparsed)--testRejectInvalidConceptId :: Either Text ()-testRejectInvalidConceptId =-  assertEqual (Left (InvalidConceptIdSegment "-users")) (parseConceptId "tables/-users")--testConceptIdToFilePath :: Either Text ()-testConceptIdToFilePath = do-  conceptId <- firstShow (parseConceptId "tables/users")-  assertEqual "tables/users.md" (conceptIdToFilePath conceptId)--testWalkBundleMissingRoot :: IO (Either Text ())-testWalkBundleMissingRoot = do-  temporaryDirectory <- getTemporaryDirectory-  root <- createTempDirectory temporaryDirectory "okf-core-missing-parent"-  let missingRoot = root </> "missing"-  result <- walkBundle missingRoot-  removeDirectoryRecursive root-  pure-    ( case result of-        Left (BundleIoError path message)-          | path == missingRoot && "does not exist" `Text.isInfixOf` message -> Right ()-        other -> Left ("expected missing-root BundleIoError, got " <> Text.pack (show other))-    )--testWalkBundleSkipsReserved :: IO (Either Text ())-testWalkBundleSkipsReserved =-  withFixtureBundle-    ( \root -> do-        concepts <- readBundle root-        pure (assertEqual ["datasets/sales", "tables/customers", "tables/orders"] (renderConceptId . conceptIdOf <$> concepts))-    )---- | The gap this milestone closes: @references\/attesters\/revenue.py@ is--- specification §6.3's own example of what an @attester.resource@ points at, and--- before 'walkBundleInventory' existed nothing in okf could tell whether it was--- there. It must be visible to the inventory without becoming a concept, since--- only a @.md@ file carries frontmatter to validate.-testWalkBundleInventorySeesNonMarkdown :: IO (Either Text ())-testWalkBundleInventorySeesNonMarkdown = do-  temporaryDirectory <- getTemporaryDirectory-  root <- createTempDirectory temporaryDirectory "okf-core-inventory"-  createFixtureBundle root-  createDirectoryIfMissing True (root </> "references" </> "attesters")-  Text.IO.writeFile (root </> "references" </> "attesters" </> "revenue.py") "print('receipt')\n"-  concepts <- readBundle root-  walked <- walkBundleInventory root-  removeDirectoryRecursive root-  pure-    ( do-        inventory <- firstShow walked-        assertBool-          "the .py file is in the inventory"-          (bundleInventoryMember "references/attesters/revenue.py" inventory)-        assertBool-          "the .py file is not a concept"-          (notElem "references/attesters/revenue" (renderConceptId . conceptIdOf <$> concepts))-        assertBool-          "a concept's own file is in the inventory"-          (bundleInventoryMember "tables/orders.md" inventory)-        -- A reserved file is not a concept but is still a file, so a path naming-        -- one names something that exists.-        assertBool "a reserved file is in the inventory" (bundleInventoryMember "index.md" inventory)-        assertBool-          "a file that is not there is not in the inventory"-          (not (bundleInventoryMember "references/attesters/gone.py" inventory))-        -- An in-memory bundle knows its own concepts and honestly cannot know-        -- anything else.-        let inMemory = bundleInventoryOfConcepts concepts-        assertBool-          "the in-memory inventory holds concept paths"-          (bundleInventoryMember "tables/orders.md" inMemory)-        assertBool-          "the in-memory inventory cannot know a non-Markdown file"-          (not (bundleInventoryMember "references/attesters/revenue.py" inMemory))-    )--testWalkBundleDiscoversNestedConceptIds :: IO (Either Text ())-testWalkBundleDiscoversNestedConceptIds =-  withFixtureBundle-    ( \root -> do-        concepts <- readBundle root-        pure-          ( do-              expected <- firstShow (parseConceptId "tables/orders")-              assertBool "nested concept exists" (isJust (findConcept expected concepts))-          )-    )---- | Build a throwaway directory tree, run an action on it, and clean up.-withDiscoveryTree :: String -> [(FilePath, Text)] -> (FilePath -> IO a) -> IO a-withDiscoveryTree label files action = do-  temporaryDirectory <- getTemporaryDirectory-  root <- createTempDirectory temporaryDirectory label-  for_ files $ \(relativePath, content) -> do-    createDirectoryIfMissing True (root </> takeDirectory relativePath)-    Text.IO.writeFile (root </> relativePath) content-  result <- action root-  removeDirectoryRecursive root-  pure result--typedConcept :: Text -> Text-typedConcept titleText =-  Text.unlines ["---", "type: Table", "title: " <> titleText, "---", "", "# " <> titleText]--plainMarkdown :: Text-plainMarkdown = "# Just prose\n\nNo frontmatter here.\n"--testDiscoverIndexMd :: IO (Either Text ())-testDiscoverIndexMd =-  withDiscoveryTree "okf-discovery-index" [("kb/index.md", "# Index\n")] $ \root -> do-    found <- discoverBundleRoots defaultDiscoveryOptions root-    pure (assertEqual [normalise (root </> "kb")] found)--testDiscoverTypedConcept :: IO (Either Text ())-testDiscoverTypedConcept =-  withDiscoveryTree "okf-discovery-typed" [("kb/tables/orders.md", typedConcept "Orders")] $ \root -> do-    found <- discoverBundleRoots defaultDiscoveryOptions root-    pure (assertEqual [normalise (root </> "kb" </> "tables")] found)--testDiscoverIgnoresPlainMarkdown :: IO (Either Text ())-testDiscoverIgnoresPlainMarkdown =-  withDiscoveryTree-    "okf-discovery-plain"-    [("notes/README.md", plainMarkdown), ("notes/CHANGELOG.md", plainMarkdown)]-    $ \root -> do-      found <- discoverBundleRoots defaultDiscoveryOptions root-      pure (assertEqual [] found)--testDiscoverPrunesNestedBundles :: IO (Either Text ())-testDiscoverPrunesNestedBundles =-  withDiscoveryTree-    "okf-discovery-prune"-    [ ("kb/index.md", "# Index\n"),-      ("kb/tables/index.md", "# Tables\n"),-      ("kb/tables/orders.md", typedConcept "Orders")-    ]-    $ \root -> do-      found <- discoverBundleRoots defaultDiscoveryOptions root-      pure (assertEqual [normalise (root </> "kb")] found)--testDiscoverSkipsNoise :: IO (Either Text ())-testDiscoverSkipsNoise =-  withDiscoveryTree-    "okf-discovery-noise"-    [ (".hidden/index.md", "# Hidden\n"),-      ("dist-newstyle/index.md", "# Build output\n"),-      ("kb/index.md", "# Index\n")-    ]-    $ \root -> do-      found <- discoverBundleRoots defaultDiscoveryOptions root-      pure (assertEqual [normalise (root </> "kb")] found)--testDiscoverHonoursMaxDepth :: IO (Either Text ())-testDiscoverHonoursMaxDepth =-  withDiscoveryTree "okf-discovery-depth" [("a/b/c/index.md", "# Deep\n")] $ \root -> do-    shallow <- discoverBundleRoots defaultDiscoveryOptions {maxDepth = 2} root-    deep <- discoverBundleRoots defaultDiscoveryOptions {maxDepth = 3} root-    pure (assertEqual [] shallow >> assertEqual [normalise (root </> "a" </> "b" </> "c")] deep)--testDiscoverFixtureBundle :: IO (Either Text ())-testDiscoverFixtureBundle = do-  bundle <- fixturePath "valid-bundle"-  found <- discoverBundleRoots defaultDiscoveryOptions bundle-  pure (assertEqual [normalise bundle] found)--testLogRoundTrip :: Either Text ()-testLogRoundTrip = do-  let canonicalLog =-        Text.unlines-          [ "# Directory Update Log",-            "",-            "## 2026-06-23",-            "* **Update**: Refreshed [orders](tables/orders.md).",-            "* **Creation**: Added customers.",-            "",-            "## 2026-06-01",-            "* Deprecated a stale note."-          ]-      parsed = parseLog canonicalLog-      reparsed = parseLog (serializeLog parsed)-  assertEqual-    ( Log-        { logTitle = "Directory Update Log",-          logDays =-            [ LogDay-                { logDate = "2026-06-23",-                  logEntries =-                    [ LogEntry (Just "Update") "Refreshed [orders](tables/orders.md).",-                      LogEntry (Just "Creation") "Added customers."-                    ]-                },-              LogDay-                { logDate = "2026-06-01",-                  logEntries = [LogEntry Nothing "Deprecated a stale note."]-                }-            ]-        }-    )-    parsed-  assertEqual parsed reparsed--testValidateLogNonIsoDate :: Either Text ()-testValidateLogNonIsoDate =-  assertBool-    "expected LogDateNotIso"-    (LogDateNotIso "not-a-date" `List.elem` validateLog (parseLog "# Log\n\n## not-a-date\n* **Update**: oops\n"))--testValidateLogEmptyDay :: Either Text ()-testValidateLogEmptyDay =-  assertBool-    "expected LogEmptyDay"-    (LogEmptyDay "2026-06-23" `List.elem` validateLog (parseLog "# Log\n\n## 2026-06-23\n"))--testValidateLogOutOfOrder :: Either Text ()-testValidateLogOutOfOrder =-  assertBool-    "expected LogDaysOutOfOrder"-    ( LogDaysOutOfOrder "2026-01-01" "2026-06-23"-        `List.elem` validateLog (parseLog "# Log\n\n## 2026-01-01\n* Old.\n\n## 2026-06-23\n* New.\n")-    )--testWalkLogsDiscoversNested :: IO (Either Text ())-testWalkLogsDiscoversNested = do-  temporaryDirectory <- getTemporaryDirectory-  root <- createTempDirectory temporaryDirectory "okf-core-logs"-  createDirectoryIfMissing True (root </> "tables")-  Text.IO.writeFile (root </> "log.md") "# Root Log\n\n## 2026-06-23\n* Root entry.\n"-  Text.IO.writeFile (root </> "tables" </> "log.md") "# Tables Log\n\n## 2026-06-22\n* Tables entry.\n"-  result <- walkLogs root-  removeDirectoryRecursive root-  pure-    ( case result of-        Right logs -> assertEqual ["log.md", "tables/log.md"] (logSourcePath <$> logs)-        Left bundleError -> Left ("expected logs, got " <> Text.pack (show bundleError))-    )--testLogStalenessFlagsNewerConcept :: Either Text ()-testLogStalenessFlagsNewerConcept = do-  staleId <- parseTestConceptId "stale"-  staleConcept <- testConceptWithTimestamp "stale" "2026-06-23T00:00:00Z"-  currentConcept <- testConceptWithTimestamp "current" "2026-01-01T00:00:00Z"-  let logs = [LogFile "log.md" (parseLog "# Log\n\n## 2026-06-01\n* **Update**: logged.\n")]-  assertEqual-    [ LogStaleness-        { staleConcept = staleId,-          staleConceptDate = "2026-06-23",-          staleLogPath = Just "log.md",-          staleLogDate = Just "2026-06-01"-        }-    ]-    (logStaleness [staleConcept, currentConcept] logs)---- | Staleness reads the v0.2 `generated.at` (specification section 5.2), and--- prefers it over the legacy `timestamp` it supersedes when both are present.-testLogStalenessReadsGeneratedAt :: Either Text ()-testLogStalenessReadsGeneratedAt = do-  generatedOnlyId <- parseTestConceptId "generated-only"-  bothId <- parseTestConceptId "both"-  generatedOnly <--    testConceptWithFrontmatter-      "generated-only"-      "type: Test\ngenerated: { by: human:ahormati, at: 2026-06-23T00:00:00Z }\n"-  -- `generated.at` wins over `timestamp`: the stale date must be the June 24-  -- from `generated`, not the January 1 from the legacy key.-  bothKeys <--    testConceptWithFrontmatter-      "both"-      "type: Test\ngenerated: { by: human:ahormati, at: 2026-06-24T00:00:00Z }\ntimestamp: 2026-01-01T00:00:00Z\n"-  let logs = [LogFile "log.md" (parseLog "# Log\n\n## 2026-06-01\n* **Update**: logged.\n")]-  assertEqual-    [ LogStaleness bothId "2026-06-24" (Just "log.md") (Just "2026-06-01"),-      LogStaleness generatedOnlyId "2026-06-23" (Just "log.md") (Just "2026-06-01")-    ]-    (logStaleness [bothKeys, generatedOnly] logs)--testLogStalenessPrefersDeepestLog :: Either Text ()-testLogStalenessPrefersDeepestLog = do-  usersId <- parseTestConceptId "tables/users"-  usersConcept <- testConceptWithTimestamp "tables/users" "2026-06-21T00:00:00Z"-  let logs =-        [ LogFile "log.md" (parseLog "# Root Log\n\n## 2026-06-01\n* **Update**: root.\n"),-          LogFile "tables/log.md" (parseLog "# Tables Log\n\n## 2026-06-20\n* **Update**: tables.\n")-        ]-  assertEqual-    [ LogStaleness-        { staleConcept = usersId,-          staleConceptDate = "2026-06-21",-          staleLogPath = Just "tables/log.md",-          staleLogDate = Just "2026-06-20"-        }-    ]-    (logStaleness [usersConcept] logs)--testAppendLogEntry :: Either Text ()-testAppendLogEntry =-  assertEqual-    ( Log-        { logTitle = "Log",-          logDays =-            [ LogDay "2026-06-23" [LogEntry (Just "Update") "new"],-              LogDay "2026-06-01" [LogEntry (Just "Update") "prepended", LogEntry (Just "Creation") "old"]-            ]-        }-    )-    ( appendLogEntry-        "2026-06-01"-        (LogEntry (Just "Update") "prepended")-        ( appendLogEntry-            "2026-06-23"-            (LogEntry (Just "Update") "new")-            (Log "Log" [LogDay "2026-06-01" [LogEntry (Just "Creation") "old"]])-        )-    )--testGenerateIndexGroupsByType :: IO (Either Text ())-testGenerateIndexGroupsByType =-  withFixtureBundle-    ( \root -> do-        concepts <- readBundle root-        pure-          ( do-              orders <- requireConcept "tables/orders" concepts-              customers <- requireConcept "tables/customers" concepts-              let rendered = renderIndex [] [] [orders, customers]-              assertBool "has type heading" ("# BigQuery Table" `Text.isInfixOf` rendered)-              assertBool "has orders bullet" ("[Orders](orders.md) - Order records." `Text.isInfixOf` rendered)-              assertBool "has customers bullet" ("[Customers](customers.md) - Customer records." `Text.isInfixOf` rendered)-              -- §8's progressive disclosure reaches a file with no frontmatter:-              -- a directory holding only an attester used to render one newline.-              let withFiles = renderIndex [] ["revenue.py"] []-              -- The trailing blank line is 'renderIndex''s own, appended after-              -- every section; a concepts-only index ends the same way.-              assertEqual "# Files\n\n- [revenue.py](revenue.py)\n\n" withFiles-          )-    )--testExtractLinksResolveBundleLinks :: IO (Either Text ())-testExtractLinksResolveBundleLinks =-  withFixtureBundle-    ( \root -> do-        concepts <- readBundle root-        pure-          ( do-              orders <- requireConcept "tables/orders" concepts-              customers <- firstShow (parseConceptId "tables/customers")-              sales <- firstShow (parseConceptId "datasets/sales")-              let links = extractConceptLinks orders-              assertBool "absolute or ./ customers link" (customers `List.elem` links)-              assertBool "../ sales link" (sales `List.elem` links)-          )-    )--testExtractLinksIgnoresExternalUrls :: IO (Either Text ())-testExtractLinksIgnoresExternalUrls =-  withFixtureBundle-    ( \root -> do-        concepts <- readBundle root-        pure-          ( do-              orders <- requireConcept "tables/orders" concepts-              assertEqual 4 (length (extractConceptLinks orders))-          )-    )--testBuildGraphIncludesKnownEdges :: IO (Either Text ())-testBuildGraphIncludesKnownEdges =-  withFixtureBundle-    ( \root -> do-        concepts <- readBundle root-        pure-          ( do-              orders <- firstShow (parseConceptId "tables/orders")-              customers <- firstShow (parseConceptId "tables/customers")-              missing <- firstShow (parseConceptId "missing")-              let graph = buildGraph concepts-              assertEqual 3 (length (nodes graph))-              assertBool "known edge exists" (Edge {source = orders, target = customers} `List.elem` edges graph)-              assertBool "broken edge excluded" (Edge {source = orders, target = missing} `notElem` edges graph)-          )-    )--testWriteBundleIndexesDeterministic :: IO (Either Text ())-testWriteBundleIndexesDeterministic =-  withFixtureBundle-    ( \root -> do-        firstResult <- writeBundleIndexes root-        firstIndex <- Text.IO.readFile (root </> "tables" </> "index.md")-        secondResult <- writeBundleIndexes root-        secondIndex <- Text.IO.readFile (root </> "tables" </> "index.md")-        pure-          ( do-              firstShow firstResult-              firstShow secondResult-              assertEqual firstIndex secondIndex-              assertBool "tables index has BigQuery Table section" ("# BigQuery Table" `Text.isInfixOf` secondIndex)-          )-    )---- | Specification §12 permits a bundle-root @index.md@ to declare the version--- it targets. Every shape of that declaration is readable and none is fatal.-testReadBundleVersion :: IO (Either Text ())-testReadBundleVersion = do-  declared <- versionOf [("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Root\n")]-  noKey <- versionOf [("index.md", "---\ntitle: Root\n---\n\n# Root\n")]-  noFrontmatter <- versionOf [("index.md", "# Root\n")]-  noIndex <- versionOf [("kb.md", "# Not an index\n")]-  unparseable <- versionOf [("index.md", "---\nokf_version: \"zero point two\"\n---\n\n# Root\n")]-  malformed <- versionOf [("index.md", "---\nokf_version: \"0.2\"\n\n# Root\n")]-  pure $ do-    assertEqual (Right (VersionDeclared (OkfVersion 0 2))) declared-    assertEqual (Right VersionUndeclared) noKey-    assertEqual (Right VersionUndeclared) noFrontmatter-    assertEqual (Right VersionUndeclared) noIndex-    assertEqual (Right (VersionUnparseable "zero point two")) unparseable-    assertEqual (Right VersionUndeclared) malformed---- | A careless author writes @okf_version: 0.2@ without quotes, which YAML--- reads as a float. A bundle should not be unreadable over missing quotes.-testReadBundleVersionUnquoted :: IO (Either Text ())-testReadBundleVersionUnquoted = do-  unquoted <- versionOf [("index.md", "---\nokf_version: 0.2\n---\n\n# Root\n")]-  pure (assertEqual (Right (VersionDeclared (OkfVersion 0 2))) unquoted)--versionOf :: [(FilePath, Text)] -> IO (Either BundleError VersionDeclaration)-versionOf files =-  withDiscoveryTree "okf-version" files readBundleVersion---- | Index generation rewrites the bundle root's @index.md@, so without reading--- the existing declaration first a single write destroys it. Fails on the code--- that preceded this test.-testWriteBundleIndexesPreservesVersion :: IO (Either Text ())-testWriteBundleIndexesPreservesVersion =-  withDiscoveryTree-    "okf-version-preserve"-    [ ("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Root\n"),-      ("tables/orders.md", typedConcept "Orders")-    ]-    ( \root -> do-        written <- writeBundleIndexes root-        rootIndex <- Text.IO.readFile (root </> "index.md")-        tablesIndex <- Text.IO.readFile (root </> "tables" </> "index.md")-        declaration <- readBundleVersion root-        pure-          ( do-              firstShow written-              assertEqual (Right (VersionDeclared (OkfVersion 0 2))) declaration-              assertBool "root index keeps the declaration" ("okf_version: \"0.2\"" `Text.isInfixOf` rootIndex)-              assertBool "root index still lists subdirectories" ("[tables/](tables/index.md)" `Text.isInfixOf` rootIndex)-              assertBool "only the root index carries frontmatter" (not ("---" `Text.isInfixOf` tablesIndex))-          )-    )---- | An explicit declaration is written where there was none; a bundle that--- declares nothing keeps a frontmatter-free root index.-testWriteBundleIndexesDeclaresVersion :: IO (Either Text ())-testWriteBundleIndexesDeclaresVersion =-  withDiscoveryTree-    "okf-version-declare"-    [("tables/orders.md", typedConcept "Orders")]-    ( \root -> do-        untouched <- writeBundleIndexes root-        withoutDeclaration <- Text.IO.readFile (root </> "index.md")-        declared <- writeBundleIndexesWith (Just (OkfVersion 0 2)) root-        withDeclaration <- Text.IO.readFile (root </> "index.md")-        pure-          ( do-              firstShow untouched-              firstShow declared-              assertBool "undeclared bundle gets no frontmatter" (not ("---" `Text.isInfixOf` withoutDeclaration))-              assertEqual-                ("---\nokf_version: \"0.2\"\n---\n\n" <> withoutDeclaration)-                withDeclaration-          )-    )--testFixtureValidBundle :: IO (Either Text ())-testFixtureValidBundle = do-  root <- fixturePath "valid-bundle"-  concepts <- readBundle root-  inventory <- readBundleInventory root-  declaration <- readBundleVersion root-  pure-    ( do-        orders <- firstShow (parseConceptId "tables/orders")-        customers <- firstShow (parseConceptId "tables/customers")-        sales <- firstShow (parseConceptId "datasets/sales")-        assertEqual 4 (length concepts)-        assertEqual [] (foldMap (validateDocument PermissiveConformance . conceptDocument) concepts)-        -- The primary fixture is a v0.2 bundle: it declares the version and-        -- every concept dates itself with `generated` rather than the-        -- superseded `timestamp`.-        assertEqual (Right (VersionDeclared (OkfVersion 0 2))) declaration-        assertEqual [] (validateBundle StrictAuthoring (VersionDeclared (OkfVersion 0 2)) inventory concepts)-        assertBool-          "every concept carries generated"-          (all (isJust . conceptGenerated) concepts)-        let graph = buildGraph concepts-        assertBool "orders to customers" (Edge {source = orders, target = customers} `List.elem` edges graph)-        assertBool "orders to sales" (Edge {source = orders, target = sales} `List.elem` edges graph)-    )---- | The v0.1 fallback of @docs\/adr\/7-okf-v0-1-legacy-fallback-policy.md@ needs--- a bundle in the old shape or it will rot. This fixture is that bundle, and is--- deliberately never migrated: it dates its concept with the superseded--- @timestamp@ and declares no @okf_version@, so strict validation must report--- nothing at all.-testFixtureV01LegacyBundle :: IO (Either Text ())-testFixtureV01LegacyBundle = do-  root <- fixturePath "v01-legacy-bundle"-  concepts <- readBundle root-  inventory <- readBundleInventory root-  declaration <- readBundleVersion root-  pure-    ( do-        assertEqual 1 (length concepts)-        assertEqual (Right VersionUndeclared) declaration-        assertEqual [] (validateBundle StrictAuthoring VersionUndeclared inventory concepts)-        assertBool-          "the concept carries no generated family"-          (all (isNothing . conceptGenerated) concepts)-        -- The date is still read, which is the whole point of the fallback.-        assertEqual ["2026-06-16"] (staleConceptDate <$> logStaleness concepts [])-    )--testFixtureGraphJsonShape :: IO (Either Text ())-testFixtureGraphJsonShape = do-  root <- fixturePath "valid-bundle"-  concepts <- readBundle root-  orders <- requireConceptIO "tables/orders" concepts-  pure-    ( case filter (\Node {id = nodeId} -> nodeId == conceptIdOf orders) (nodes (buildGraph concepts)) of-        [ordersNode] ->-          assertEqual-            ( object-                [ "id" .= ("tables/orders" :: Text),-                  "label" .= ("Orders" :: Text),-                  "type" .= ("BigQuery Table" :: Text),-                  "description" .= Just ("Order fact table." :: Text),-                  "resource" .= Just ("bigquery://analytics.tables.orders" :: Text),-                  "tags" .= ["orders" :: Text, "sales"]-                ]-            )-            (toJSON ordersNode)-        other -> Left ("expected one orders node, got " <> Text.pack (show (length other)))-    )--testFixtureUnterminatedFrontmatter :: IO (Either Text ())-testFixtureUnterminatedFrontmatter = do-  root <- fixturePath "invalid-unterminated-frontmatter"-  result <- walkBundle root-  pure-    ( case result of-        Left (InvalidConceptDocument "broken.md" UnterminatedFrontmatter) -> Right ()-        other -> Left ("expected unterminated frontmatter error, got " <> Text.pack (show other))-    )--testFixtureMissingType :: IO (Either Text ())-testFixtureMissingType = do-  root <- fixturePath "invalid-missing-type"-  concepts <- readBundle root-  pure-    ( do-        assertEqual 1 (length concepts)-        case foldMap (validateDocument PermissiveConformance . conceptDocument) concepts of-          [MissingRequiredField "type"] -> Right ()-          other -> Left ("expected missing type error, got " <> Text.pack (show other))-    )--testFrontmatterBuilderRoundTrip :: Either Text ()-testFrontmatterBuilderRoundTrip = do-  let generatedValue = Generated (parseActor "reference_agent/gemini-2.5-pro") (Just "2026-06-20T22:53:05Z")-      frontmatterValue =-        setField "version" (String "0.2.0")-          . setTags ["orders", "sales"]-          . setResource "bigquery://analytics.tables.orders"-          . setGenerated generatedValue-          $ okfCommon-            OkfCommon-              { commonType = "BigQuery Table",-                commonTitle = Just "Orders",-                commonDescription = Just "Order fact table.",-                commonTimestamp = Just "2026-06-16T00:00:00Z"-              }-      original = OKFDocument frontmatterValue "# Orders\n\nBody text.\n"-  reparsed <- firstShow (parseDocument (serializeDocument original))-  assertEqual (original ^. #frontmatter) (reparsed ^. #frontmatter)-  assertEqual (body original) (body reparsed)-  -- The v0.2 family survives serialize-then-parse as a typed value, not merely-  -- as equal frontmatter, and a `generated` without `at` round-trips too.-  assertEqual (Just generatedValue) (readGenerated (reparsed ^. #frontmatter))-  let withoutAt = setGenerated (Generated (HumanActor "ahormati") Nothing) emptyFrontmatter-  reparsedWithoutAt <- firstShow (parseDocument (serializeDocument (OKFDocument withoutAt "# Orders\n")))-  assertEqual-    (Just (Generated (HumanActor "ahormati") Nothing))-    (readGenerated (reparsedWithoutAt ^. #frontmatter))--testSerializeDeterministicKeyOrder :: Either Text ()-testSerializeDeterministicKeyOrder = do-  let frontmatterValue =-        setField "zeta" (String "z")-          . setField "alpha" (String "a")-          . setTags ["t"]-          . setResource "res://x"-          . setType "Recipe"-          . setTimestamp "2026-06-16T00:00:00Z"-          . setDescription "Desc"-          . setTitle "Demo"-          $ emptyFrontmatter-      rendered = serializeDocument (OKFDocument frontmatterValue "# Demo\n")-      expectedOrder =-        ["type:", "title:", "description:", "resource:", "tags:", "timestamp:", "alpha:", "zeta:"]-  keyIndices <- traverse (\key -> maybe (Left ("missing key " <> key)) Right (substringIndex key rendered)) expectedOrder-  assertBool ("keys not in deterministic order: " <> Text.pack (show keyIndices)) (strictlyIncreasing keyIndices)---- | The v0.2 @generated@ family sorts before the v0.1 @timestamp@ it supersedes--- (specification section 13.1), so a document carrying both reads with the--- current field first.-testSerializeGeneratedBeforeTimestamp :: Either Text ()-testSerializeGeneratedBeforeTimestamp = do-  let frontmatterValue =-        setTimestamp "2026-06-16T00:00:00Z"-          . setField "generated" (object ["by" .= ("human:ahormati" :: Text), "at" .= ("2026-06-20T22:53:05Z" :: Text)])-          . setType "Recipe"-          $ emptyFrontmatter-      rendered = serializeDocument (OKFDocument frontmatterValue "# Demo\n")-      expectedOrder = ["type:", "generated:", "timestamp:"]-  keyIndices <- traverse (\key -> maybe (Left ("missing key " <> key)) Right (substringIndex key rendered)) expectedOrder-  assertBool ("keys not in deterministic order: " <> Text.pack (show keyIndices)) (strictlyIncreasing keyIndices)---- | Footnotes are enabled at every parse site, and the observable proof is a--- link that no longer appears.------ With footnotes disabled a single-token footnote definition such as--- @[^src]: tables\/orders.md@ is read as a CommonMark /link reference--- definition/, which turns its citation @[^src]@ into a link whose destination--- is that token. That phantom link reached 'extractConceptLinks' and was then--- reported as a dangling reference. Enabling footnotes removes it while leaving--- an ordinary link in the same body alone.-testFootnotesEnabled :: Either Text ()-testFootnotesEnabled = do-  ordersId <- parseTestConceptId "tables/orders"-  usersId <- parseTestConceptId "tables/users"-  concept <--    testConcept-      "source"-      ( "See the note.[^src] Also see "-          <> renderConceptLink usersId "users"-          <> ".\n\n[^src]: tables/orders.md\n"-      )-  assertEqual [usersId] (extractConceptLinks concept)-  assertBool-    "footnote definition must not become a link reference definition"-    (ordersId `notElem` extractConceptLinks concept)---- | Enabling footnotes changes the parse tree every body walker sees, so pin--- the two walkers that do not care about footnotes at all: log parsing and link--- extraction. Bracket-heavy prose in a log bullet must still yield one entry--- with its text intact, and a body whose links sit inside a /cited/ footnote--- definition must still contribute those links to the graph.-testFootnotesDoNotRegressLogsOrLinks :: Either Text ()-testFootnotesDoNotRegressLogsOrLinks = do-  let parsed = parseLog "# Log\n\n## 2026-06-23\n* **Update**: renamed [orders] to [^orders].\n"-  -- The backslashes are 'Okf.Log.renderInlineNodes' round-tripping inline nodes-  -- through @nodeToCommonmark@, which escapes brackets so the text re-parses to-  -- itself. That predates footnotes and is unchanged by them: an uncited-  -- @[^orders]@ is plain text under either parse configuration.-  assertEqual-    [LogDay "2026-06-23" [LogEntry (Just "Update") "renamed \\[orders\\] to \\[^orders\\]."]]-    (logDays parsed)-  usersId <- parseTestConceptId "tables/users"-  concept <--    testConcept-      "source"-      ( "Attributed claim.[^cited]\n\n[^cited]: See "-          <> renderConceptLink usersId "users"-          <> " for detail.\n"-      )-  assertEqual [usersId] (extractConceptLinks concept)---- | Labels come from a real parse, not a naive text scan: footnote syntax--- inside an inline code span, an indented code block, or a fenced code block--- yields nothing.-testExtractFootnoteLabelsIgnoresCode :: Either Text ()-testExtractFootnoteLabelsIgnoresCode = do-  let body =-        Text.unlines-          [ "Sharded daily.[^ga4-schema] Not a footnote: `[^inline-code]`.",-            "",-            "    [^indented-block]: not a footnote either",-            "",-            "```sql",-            "SELECT 1 -- [^fenced-block]: not a footnote",-            "```",-            "",-            "Undefined citation.[^never-defined]",-            "",-            "[^ga4-schema]: GA4 BigQuery Export schema"-          ]-      labels = extractFootnoteLabels body-  assertEqual ["ga4-schema", "never-defined"] (footnoteReferences labels)-  assertEqual ["ga4-schema"] (footnoteDefinitions labels)-  assertEqual ["ga4-schema", "never-defined"] (footnoteLabelsUsed labels)---- | The two labels cmark-gfm erases are exactly the two an author most needs--- reported, so extraction must keep both: a citation with no definition (which--- the parser reverts to plain text) and a definition nothing cites (which the--- parser deletes outright). The ordinal guard is the same test's second job —--- cmark-gfm renumbers a matched reference to @"1"@, so a label that parses as a--- bare integer would mean extraction had drifted back onto the parse tree.-testExtractFootnoteLabelsKeepsErasedLabels :: Either Text ()-testExtractFootnoteLabelsKeepsErasedLabels = do-  let body =-        Text.unlines-          [ "Matched.[^matched] Undefined.[^undefined]",-            "",-            "[^matched]: a definition that is cited",-            "",-            "[^uncited]: a definition that nothing cites"-          ]-      labels = extractFootnoteLabels body-  assertEqual ["matched", "undefined"] (footnoteReferences labels)-  assertEqual ["matched", "uncited"] (footnoteDefinitions labels)-  assertBool-    "no extracted label may be a bare ordinal"-    (not (any looksLikeInteger (footnoteLabelsUsed labels)))-  where-    looksLikeInteger label =-      not (Text.null label) && Text.all (`Text.elem` "0123456789") label---- | Specification §10.3's prose says "fenced" and §10.2's own worked example--- writes an indented block, so both count; and the section is bounded at the--- next heading of the same or a shallower level, so a fenced block under a later--- @# Notes@ heading is not a second computation while one under a nested--- @## Subsection@ still belongs to the section.-testComputationBlocks :: Either Text ()-testComputationBlocks = do-  assertEqual-    ["SELECT 1\n"]-    (computationBlocks (Text.unlines ["# Computation", "", "    SELECT 1"]))-  assertEqual-    ["SELECT 1\n"]-    (computationBlocks (Text.unlines ["# Computation", "", "```sql", "SELECT 1", "```"]))-  assertEqual-    ["SELECT 1\n"]-    ( computationBlocks-        ( Text.unlines-            [ "# Computation",-              "",-              "    SELECT 1",-              "",-              "# Notes",-              "",-              "```sql",-              "SELECT 2",-              "```"-            ]-        )-    )-  assertEqual-    ["SELECT 1\n", "SELECT 2\n"]-    ( computationBlocks-        ( Text.unlines-            [ "# Computation",-              "",-              "    SELECT 1",-              "",-              "## Explanation",-              "",-              "```sql",-              "SELECT 2",-              "```"-            ]-        )-    )-  assertEqual-    ["SELECT 1\n", "SELECT 2\n"]-    ( computationBlocks-        ( Text.unlines-            ["# Computation", "", "```sql", "SELECT 1", "```", "", "```sql", "SELECT 2", "```"]-        )-    )-  assertEqual-    []-    (computationBlocks (Text.unlines ["# Notes", "", "```sql", "SELECT 1", "```"]))-  assertEqual-    ["SELECT 1\n"]-    (computationBlocks (Text.unlines ["##  computation ", "", "    SELECT 1"]))---- | The one erasure that reaches 'computationBlocks', pinned so that meeting it--- later is recognized rather than investigated. Per--- @docs/adr/9-one-markdown-parse-configuration-and-source-scanned-authoring-checks.md@,--- okf parses every body with footnotes enabled and cmark-gfm deletes a footnote--- definition nothing cites, content and all — so a computation hidden inside one--- is invisible here. The document is malformed in a second, unrelated way, so--- this is an accepted cost rather than a bug to work around.-testComputationBlocksFootnoteHazard :: Either Text ()-testComputationBlocksFootnoteHazard =-  assertEqual-    []-    ( computationBlocks-        ( Text.unlines-            ["# Computation", "", "[^unused]: a definition nothing cites", "", "    SELECT 1"]-        )-    )--testConceptLinkRoundTrip :: Either Text ()-testConceptLinkRoundTrip = do-  sourceId <- parseTestConceptId "recipes/haskell-library-repo"-  let targetStrings = ["orders", "modules/nix-haskell-flake", "refs/source-system.v1"]-  mapM_-    ( \rawTarget -> do-        targetId <- parseTestConceptId rawTarget-        let extracted = extractFromBodyLinkingTo sourceId targetId-        assertEqual [targetId] extracted-    )-    targetStrings--parseTestConceptId :: Text -> Either Text ConceptId-parseTestConceptId rawId =-  first (\err -> "bad concept id " <> rawId <> ": " <> Text.pack (show err)) (parseConceptId rawId)--extractFromBodyLinkingTo :: ConceptId -> ConceptId -> [ConceptId]-extractFromBodyLinkingTo sourceId targetId =-  extractConceptLinks-    (conceptFromDocument sourceId (OKFDocument (setType "Test" emptyFrontmatter) ("See " <> renderConceptLink targetId "link" <> ".\n")))--testRejectOverEscapingRelativeLink :: Either Text ()-testRejectOverEscapingRelativeLink = do-  sourceId <- parseTestConceptId "a/b/source"-  targetId <- parseTestConceptId "tables/orders"-  let concept =-        conceptFromDocument-          sourceId-          (OKFDocument (setType "Test" emptyFrontmatter) "[Escapes](../../../tables/orders.md)\n")-  assertEqual [] (extractConceptLinks concept)-  assertEqual [] (validateInMemoryBundle PermissiveConformance VersionUndeclared [concept, targetConcept targetId])-  where-    targetConcept targetId =-      conceptFromDocument-        targetId-        (OKFDocument (setType "Test" emptyFrontmatter) "# Orders\n")---- | Specification §6.2: each path-valued field accepts an absolute URL, a--- bundle-relative path beginning with @/@, or an ordinary relative path.--- Classification is total, so a value that is none of the three lands on a named--- alternative rather than being dropped.-testClassifyPathReference :: Either Text ()-testClassifyPathReference = do-  deep <- parseTestConceptId "metrics/finance/revenue"-  shallow <- parseTestConceptId "revenue"-  -- An absolute URL yields its case-folded scheme, whatever the scheme is: §6.2-  -- names no allowed set, so deciding that is the profile's job.-  assertEqual (ExternalUrl "https") (classifyPathReference deep "https://wiki.acme/revenue")-  assertEqual (ExternalUrl "mori") (classifyPathReference deep "mori://shinzui/okf")-  assertEqual (ExternalUrl "https") (classifyPathReference deep "HTTPS://wiki.acme/revenue")-  -- A leading slash resolves from the bundle root regardless of where the-  -- concept carrying the value lives.-  assertEqual (BundlePath "references/policy.md") (classifyPathReference deep "/references/policy.md")-  assertEqual (BundlePath "references/policy.md") (classifyPathReference shallow "/references/policy.md")-  -- A relative path resolves against the source concept's own directory.-  assertEqual-    (BundlePath "metrics/finance/policy.md")-    (classifyPathReference deep "policy.md")-  assertEqual-    (BundlePath "metrics/computations/revenue.md")-    (classifyPathReference deep "../computations/revenue.md")-  assertEqual (BundlePath "policy.md") (classifyPathReference shallow "./policy.md")-  -- A fragment or query suffix names the same target as the bare path.-  assertEqual (BundlePath "references/policy.md") (classifyPathReference deep "/references/policy.md#recognition")-  assertEqual (BundlePath "references/policy.md") (classifyPathReference deep "/references/policy.md?v=2")-  -- Non-Markdown targets classify identically; only the caller cares about the-  -- extension.-  assertEqual-    (BundlePath "references/attesters/revenue.py")-    (classifyPathReference deep "/references/attesters/revenue.py")-  -- Climbing above the bundle root is its own outcome, distinct from malformed:-  -- the author wrote a well-formed relative path that points outside.-  assertEqual EscapesBundle (classifyPathReference shallow "../../etc/passwd")-  assertEqual EscapesBundle (classifyPathReference deep "../../../../elsewhere.md")-  -- Text that names nothing at all.-  assertEqual MalformedPath (classifyPathReference deep "")-  assertEqual MalformedPath (classifyPathReference deep "   ")-  assertEqual MalformedPath (classifyPathReference deep "#recognition")-  -- 'collapseBundlePath' is exported for the same reason it is shared: one-  -- spelling of "does this climb out of the bundle".-  assertEqual (Just "references/policy.md") (collapseBundlePath "references/./policy.md")-  assertEqual (Just "policy.md") (collapseBundlePath "references/../policy.md")-  assertEqual Nothing (collapseBundlePath "../policy.md")---- | The seam 'Okf.Path' deliberately left open: classification says what shape a--- value has, resolution says whether the thing it names is there. The predicate--- stands in for a 'BundleInventory' so the two can be tested apart.-testResolvePathReference :: Either Text ()-testResolvePathReference = do-  deep <- parseTestConceptId "metrics/finance/revenue"-  shallow <- parseTestConceptId "revenue"-  let present =-        [ "references/policy.md",-          "references/attesters/revenue.py",-          "metrics/finance/policy.md",-          "sibling.md"-        ]-      exists = (`elem` present)-      resolve = resolvePathReference exists-  -- Every scheme counts, not only the three 'Okf.Graph.isExternalUrl' knows-  -- about, and okf never fetches any of them.-  assertEqual (ResolvedExternal "https") (resolve deep "https://wiki.acme/revenue")-  assertEqual (ResolvedExternal "bigquery") (resolve deep "bigquery://analytics.tables.orders")-  -- A leading slash resolves from the bundle root wherever the concept lives.-  assertEqual (ResolvedInBundle "references/policy.md") (resolve deep "/references/policy.md")-  assertEqual (ResolvedInBundle "references/policy.md") (resolve shallow "/references/policy.md")-  -- A relative path resolves against the carrying concept's own directory.-  assertEqual (ResolvedInBundle "metrics/finance/policy.md") (resolve deep "policy.md")-  assertEqual (ResolvedInBundle "sibling.md") (resolve shallow "./sibling.md")-  -- The case this whole plan exists for: a non-Markdown target resolves, which-  -- is only possible because the inventory sees more than concepts.-  assertEqual-    (ResolvedInBundle "references/attesters/revenue.py")-    (resolve deep "/references/attesters/revenue.py")-  -- Nothing there under that name.-  assertEqual (DanglingInBundle "references/deleted.md") (resolve deep "/references/deleted.md")-  assertEqual (DanglingInBundle "metrics/computations/revenue.md") (resolve deep "../computations/revenue.md")-  -- Distinct outcomes for a value that could never name anything in the bundle.-  assertEqual UnresolvableEscape (resolve shallow "../../etc/passwd")-  assertEqual UnresolvableMalformed (resolve deep "")-  assertEqual UnresolvableMalformed (resolve deep "   ")---- | The version-metadata lists name keys okf actually owns. Nothing else would--- catch a typo in one of those string literals: a misspelled entry simply never--- matches a rule, so the check it drives goes quietly missing.-testVersionedFieldsAreCoreFields :: Either Text ()-testVersionedFieldsAreCoreFields = do-  assertEqual [] (filter (`Set.notMember` coreFrontmatterFields) fieldsIntroducedInV02)-  assertEqual [] (filter (`Set.notMember` coreFrontmatterFields) fieldsSupersededInV02)-  -- The two lists are about different versions of the same key set and must not-  -- overlap: a key cannot be both introduced and superseded by v0.2.-  assertEqual [] (filter (`elem` fieldsSupersededInV02) fieldsIntroducedInV02)---- | Specification §12: a known major with a higher minor is read as the highest--- version okf understands within that major, because a minor bump is defined as--- backward-compatible additions. An unknown major is read with no--- version-specific rules at all.-testVersionGate :: Either Text ()-testVersionGate = do-  assertEqual Nothing (gateEffective (versionGate VersionUndeclared))-  assertEqual Nothing (gateEffective (versionGate (VersionUnparseable "zero point two")))-  assertEqual (Just (OkfVersion 0 1)) (gateEffective (versionGate (VersionDeclared (OkfVersion 0 1))))-  assertEqual (Just (OkfVersion 0 2)) (gateEffective (versionGate (VersionDeclared (OkfVersion 0 2))))-  assertEqual (Just (OkfVersion 0 2)) (gateEffective (versionGate (VersionDeclared (OkfVersion 0 3))))-  assertEqual Nothing (gateEffective (versionGate (VersionDeclared (OkfVersion 1 0))))-  assertEqual (Just "1.0") (gateNotUnderstood (versionGate (VersionDeclared (OkfVersion 1 0))))-  assertEqual Nothing (gateNotUnderstood (versionGate (VersionDeclared (OkfVersion 0 3))))-  assertBool "0.2 satisfies at-least 0.2" (gateDeclaresAtLeast (OkfVersion 0 2) (versionGate (VersionDeclared (OkfVersion 0 2))))-  assertBool "0.1 does not satisfy at-least 0.2" (not (gateDeclaresAtLeast (OkfVersion 0 2) (versionGate (VersionDeclared (OkfVersion 0 1)))))-  assertBool "undeclared satisfies nothing" (not (gateDeclaresAtLeast (OkfVersion 0 2) (versionGate VersionUndeclared)))---- | The asymmetry this plan exists for: the v0.1 fallback stays unconditional,--- but a bundle that has declared v0.2 and still carries @timestamp@ is--- reporting an authoring mistake.-testLegacyFieldInDeclaredV2 :: Either Text ()-testLegacyFieldInDeclaredV2 = do-  conceptId <- parseTestConceptId "tables/orders"-  legacyOnly <--    testConceptWithFrontmatter-      "tables/orders"-      "type: Test\ntitle: Title\ndescription: Description\ntimestamp: \"2026-06-16T00:00:00Z\"\n"-  migrated <--    testConceptWithFrontmatter-      "tables/orders"-      "type: Test\ntitle: Title\ndescription: Description\ngenerated:\n  by: okf/0.4\n  at: \"2026-06-16T00:00:00Z\"\n"-  let declaredV2 = VersionDeclared (OkfVersion 0 2)-  assertEqual [] (validateInMemoryBundle StrictAuthoring VersionUndeclared [legacyOnly])-  assertEqual [] (validateInMemoryBundle PermissiveConformance declaredV2 [legacyOnly])-  assertEqual-    [DocumentInvalid conceptId (LegacyFieldInDeclaredV2 "timestamp")]-    (validateInMemoryBundle StrictAuthoring declaredV2 [legacyOnly])-  assertEqual [] (validateInMemoryBundle StrictAuthoring declaredV2 [migrated])-  -- An unknown major applies no version-specific rule, so the same document is-  -- read the way an undeclared bundle's would be.-  assertEqual-    [BundleVersionNotUnderstood "1.0"]-    (validateInMemoryBundle StrictAuthoring (VersionDeclared (OkfVersion 1 0)) [legacyOnly])---- | §12: "Consumers that do not understand the declared version SHOULD attempt--- best-effort consumption rather than refusing the bundle." Neither an--- unreadable value nor an unknown major stops the bundle being read, and--- neither is reported outside strict authoring.-testVersionDeclarationLints :: Either Text ()-testVersionDeclarationLints = do-  -- A migrated concept, so the only diagnostics here are version ones.-  concept <--    testConceptWithFrontmatter-      "a"-      "type: Test\ntitle: Title\ndescription: Description\ngenerated:\n  by: okf/0.4\n  at: \"2026-06-16T00:00:00Z\"\n"-  assertEqual [] (validateInMemoryBundle PermissiveConformance (VersionUnparseable "0.x") [concept])-  assertEqual [] (validateInMemoryBundle PermissiveConformance (VersionDeclared (OkfVersion 1 0)) [concept])-  assertEqual-    [BundleVersionUnparseable "0.x"]-    (validateInMemoryBundle StrictAuthoring (VersionUnparseable "0.x") [concept])-  assertEqual-    [BundleVersionNotUnderstood "1.0"]-    (validateInMemoryBundle StrictAuthoring (VersionDeclared (OkfVersion 1 0)) [concept])-  -- A higher minor within a known major is a supported case, not a problem.-  assertEqual [] (validateInMemoryBundle StrictAuthoring (VersionDeclared (OkfVersion 0 3)) [concept])--testValidateBundleDanglingReference :: Either Text ()-testValidateBundleDanglingReference = do-  aId <- parseTestConceptId "a"-  bId <- parseTestConceptId "b"-  conceptA <- testConcept "a" ("See " <> renderConceptLink bId "b" <> ".\n")-  assertEqual [DanglingReference aId bId] (validateInMemoryBundle StrictAuthoring VersionUndeclared [conceptA])--testValidateBundleAcceptsResolved :: Either Text ()-testValidateBundleAcceptsResolved = do-  bId <- parseTestConceptId "b"-  conceptA <- testConcept "a" ("See " <> renderConceptLink bId "b" <> ".\n")-  conceptB <- testConcept "b" "Standalone.\n"-  assertEqual [] (validateInMemoryBundle StrictAuthoring VersionUndeclared [conceptA, conceptB])---- | The §6.2 path check, at the level where its placement decisions live: strict--- only, dangling only, and never over @sources[].resource@.-testValidateBundleDanglingFrontmatterPath :: Either Text ()-testValidateBundleDanglingFrontmatterPath = do-  aId <- parseTestConceptId "a"-  conceptB <- testConcept "b" "Standalone.\n"-  let withResource value =-        testConceptWithFrontmatter-          "a"-          ( "type: Test\ntitle: Title\ndescription: Description\n"-              <> "generated:\n  by: okf/0.4\n  at: \"2026-06-16T00:00:00Z\"\n"-              <> "resource: "-              <> value-              <> "\n"-          )-      strict concepts = validateInMemoryBundle StrictAuthoring VersionUndeclared concepts-      permissive concepts = validateInMemoryBundle PermissiveConformance VersionUndeclared concepts-  danglingResource <- withResource "/references/deleted.md"-  resolvedResource <- withResource "/b.md"-  externalResource <- withResource "bigquery://analytics.tables.orders"-  escapingResource <- withResource "../../elsewhere.md"-  assertEqual-    [DanglingFrontmatterPath aId "resource" "references/deleted.md" Nothing]-    (strict [danglingResource, conceptB])-  -- §11 forbids rejecting a bundle over a broken cross-link, so nothing is-  -- reported outside strict authoring.-  assertEqual [] (permissive [danglingResource, conceptB])-  assertEqual [] (strict [resolvedResource, conceptB])-  -- okf has no network access and never fetches, so an absolute URL is as-  -- resolved as it gets — whatever its scheme.-  assertEqual [] (strict [externalResource, conceptB])-  -- Escaping is deliberately unreported: a bare §4.1 URI such as-  -- @analytics.tables.orders@ classifies as a bundle path, so reporting any-  -- outcome other than dangling would fire on correct documents.-  assertEqual [] (strict [escapingResource, conceptB])-  -- The finding that scoped this check: §5.1 sanctions a scope descriptor as a-  -- @sources[].resource@, and @examples\/ddd-ordering@ carries one. Treating it-  -- as a path would report a correct bundle as broken.-  scopeDescriptor <--    testConceptWithFrontmatter-      "a"-      ( "type: Test\ntitle: Title\ndescription: Description\n"-          <> "generated:\n  by: okf/0.4\n  at: \"2026-06-16T00:00:00Z\"\n"-          <> "sources:\n"-          <> "  - resource: all order-domain terms agreed in the ordering team's glossary reviews\n"-      )-  assertEqual [] (strict [scopeDescriptor, conceptB])---- | The bundle-relative hint of specification §10.2's own worked example: a--- relative path that resolves to nothing, where the same text read from the--- bundle root names a file that is there.------ §6.2 resolution is unchanged — the diagnostic still names what the value--- actually resolved to. The fourth field only says what the author probably--- meant.-testDanglingFrontmatterPathAlternative :: Either Text ()-testDanglingFrontmatterPathAlternative = do-  computationId <- parseTestConceptId "computations/revenue"-  rootId <- parseTestConceptId "revenue"-  skill <- testConcept "references/skills/run-on-bq" "Run instructions.\n"-  let withResource rawId value =-        testConceptWithFrontmatter-          rawId-          ( "type: Test\ntitle: Title\ndescription: Description\n"-              <> "generated:\n  by: okf/0.4\n  at: \"2026-06-16T00:00:00Z\"\n"-              <> "resource: "-              <> value-              <> "\n"-          )-      strict concepts = validateInMemoryBundle StrictAuthoring VersionUndeclared concepts-  -- The specification's own spelling, from a concept in a subdirectory.-  bareReference <- withResource "computations/revenue" "references/skills/run-on-bq.md"-  assertEqual-    [ DanglingFrontmatterPath-        computationId-        "resource"-        "computations/references/skills/run-on-bq.md"-        (Just "references/skills/run-on-bq.md")-    ]-    (strict [bareReference, skill])-  -- No root-anchored reading resolves either, so there is nothing to suggest.-  noTwin <- withResource "computations/revenue" "references/skills/nonexistent.md"-  assertEqual-    [ DanglingFrontmatterPath-        computationId-        "resource"-        "computations/references/skills/nonexistent.md"-        Nothing-    ]-    (strict [noTwin, skill])-  -- A value already written from the bundle root has no alternative reading.-  alreadyAnchored <- withResource "computations/revenue" "/references/skills/deleted.md"-  assertEqual-    [DanglingFrontmatterPath computationId "resource" "references/skills/deleted.md" Nothing]-    (strict [alreadyAnchored, skill])-  -- A concept at the bundle root resolves both readings to the same path, so-  -- there is never a hint: either the file is there and nothing is reported, or-  -- it is not and the alternative names the same missing path. The guard in-  -- 'bundleRelativeAlternative' is what keeps the second case from suggesting-  -- exactly what it just rejected.-  atRoot <- withResource "revenue" "references/skills/run-on-bq.md"-  assertEqual-    [DanglingFrontmatterPath rootId "resource" "references/skills/run-on-bq.md" Nothing]-    (strict [atRoot])-  assertEqual [] (strict [atRoot, skill])--testDuplicateConceptIds :: Either Text ()-testDuplicateConceptIds = do-  aId <- parseTestConceptId "a"-  conceptA <- testConcept "a" "First.\n"-  conceptAAgain <- testConcept "a" "Second.\n"-  assertEqual [aId] (duplicateConceptIds [conceptA, conceptAAgain])---- | Build an in-memory concept via the public 'conceptFromDocument' constructor,--- so its typed fields are derived from the frontmatter and cannot diverge.--- Includes all StrictAuthoring fields so per-document validation passes and--- bundle-level checks can be isolated.-testConcept :: Text -> Text -> Either Text Concept-testConcept rawId bodyText = do-  conceptId <- parseTestConceptId rawId-  let frontmatterValue =-        okfCommon-          OkfCommon-            { commonType = "Test",-              commonTitle = Just "Title",-              commonDescription = Just "Description",-              commonTimestamp = Just "2026-06-16T00:00:00Z"-            }-  pure (conceptFromDocument conceptId (OKFDocument frontmatterValue bodyText))---- | Build a concept from raw frontmatter text, for cases where the frontmatter--- carries families the 'OkfCommon' builder does not cover.-testConceptWithFrontmatter :: Text -> Text -> Either Text Concept-testConceptWithFrontmatter rawId frontmatterText = do-  conceptId <- parseTestConceptId rawId-  document <- firstShow (parseDocument ("---\n" <> frontmatterText <> "---\n\n# Test\n"))-  pure (conceptFromDocument conceptId document)--testConceptWithTimestamp :: Text -> Text -> Either Text Concept-testConceptWithTimestamp rawId timestamp = do-  conceptId <- parseTestConceptId rawId-  let frontmatterValue =-        okfCommon-          OkfCommon-            { commonType = "Test",-              commonTitle = Just "Title",-              commonDescription = Just "Description",-              commonTimestamp = Just timestamp-            }-  pure (conceptFromDocument conceptId (OKFDocument frontmatterValue "# Test\n"))--testConceptGeneratedProjection :: Either Text ()-testConceptGeneratedProjection = do-  conceptId <- parseTestConceptId "tables/orders"-  document <--    firstShow-      ( parseDocument-          "---\ntype: BigQuery Table\ngenerated: { by: human:ahormati, at: 2026-06-20T22:53:05Z }\n---\n\n# Orders\n"-      )-  let concept = conceptFromDocument conceptId document-  assertEqual-    (Just (Generated (HumanActor "ahormati") (Just "2026-06-20T22:53:05Z")))-    (conceptGenerated concept)--testReadGeneratedWithoutActor :: Either Text ()-testReadGeneratedWithoutActor = do-  -- Section 5.2 makes `by` REQUIRED within `generated`, so a mapping without-  -- one is not a Generated. Reading is silent; reporting is validation's job.-  withoutBy <- firstShow (parseDocument "---\ntype: Recipe\ngenerated: { at: 2026-06-20T22:53:05Z }\n---\nBody\n")-  assertEqual Nothing (readGenerated (withoutBy ^. #frontmatter))-  notAMapping <- firstShow (parseDocument "---\ntype: Recipe\ngenerated: human:ahormati\n---\nBody\n")-  assertEqual Nothing (readGenerated (notAMapping ^. #frontmatter))-  -- `at` is not required within the mapping.-  withoutAt <- firstShow (parseDocument "---\ntype: Recipe\ngenerated: { by: reference_agent/gemini-2.5-pro }\n---\nBody\n")-  assertEqual-    (Just (Generated (ProducerActor "reference_agent" "gemini-2.5-pro") Nothing))-    (readGenerated (withoutAt ^. #frontmatter))---- | Specification section 5.2 permits `verified` as a list or as a single bare--- `{ by, at }` mapping, and section 11 makes normalising the bare form to a--- one-element list a consumer MUST.-testReadVerifiedShapes :: Either Text ()-testReadVerifiedShapes = do-  let verifiedIn source = readVerified . (^. #frontmatter) <$> firstShow (parseDocument source)-  asList <--    verifiedIn-      "---\ntype: Recipe\nverified:\n  - { by: human:ahormati, at: 2026-06-25T09:00:00Z }\n  - { by: process:finance-nightly, at: 2026-06-26T02:00:00Z }\n---\nBody\n"-  assertEqual-    [ Verification (HumanActor "ahormati") (Just "2026-06-25T09:00:00Z"),-      Verification (ProcessActor "finance-nightly") (Just "2026-06-26T02:00:00Z")-    ]-    asList-  bareMapping <- verifiedIn "---\ntype: Recipe\nverified: { by: human:ahormati, at: 2026-06-25T09:00:00Z }\n---\nBody\n"-  assertEqual [Verification (HumanActor "ahormati") (Just "2026-06-25T09:00:00Z")] bareMapping-  absent <- verifiedIn "---\ntype: Recipe\n---\nBody\n"-  assertEqual [] absent-  -- An entry without the `by` actor is skipped rather than yielding a partial-  -- Verification, mirroring readGenerated.-  partial <- verifiedIn "---\ntype: Recipe\nverified:\n  - { at: 2026-06-25T09:00:00Z }\n  - { by: human:ahormati }\n---\nBody\n"-  assertEqual [Verification (HumanActor "ahormati") Nothing] partial-  notAMapping <- verifiedIn "---\ntype: Recipe\nverified: human:ahormati\n---\nBody\n"-  assertEqual [] notAMapping--testVerifiedRoundTrip :: Either Text ()-testVerifiedRoundTrip = do-  let verifications =-        [ Verification (HumanActor "ahormati") (Just "2026-06-25T09:00:00Z"),-          Verification (ProcessActor "finance-nightly") Nothing-        ]-      original = OKFDocument (setVerified verifications (setType "Recipe" emptyFrontmatter)) "# Demo\n"-      rendered = serializeDocument original-  reparsed <- firstShow (parseDocument rendered)-  assertEqual verifications (readVerified (reparsed ^. #frontmatter))-  -- A single entry is still written as a list, not as the bare-mapping form.-  let single = OKFDocument (setVerified [Verification (HumanActor "ahormati") Nothing] emptyFrontmatter) "# Demo\n"-  assertBool-    ("single entry not written as a list: " <> serializeDocument single)-    (isJust (substringIndex "- by:" (serializeDocument single)))--testReadStatus :: Either Text ()-testReadStatus = do-  let statusIn source = readStatus . (^. #frontmatter) <$> firstShow (parseDocument source)-      withStatus value = statusIn ("---\ntype: Recipe\nstatus: " <> value <> "\n---\nBody\n")-  for_-    [("draft", Draft), ("stable", Stable), ("deprecated", Deprecated)]-    (\(text, expected) -> withStatus text >>= assertEqual expected)-  -- Section 5.4: "Absent `status` => `stable`."-  absent <- statusIn "---\ntype: Recipe\n---\nBody\n"-  assertEqual Stable absent-  -- Section 11 forbids rejecting for an unexpected optional value, and the-  -- original text must survive so renderStatus reproduces it.-  unknown <- withStatus "archived"-  assertEqual (UnknownStatus "archived") unknown-  assertEqual "archived" (renderStatus unknown)-  -- Case-sensitive, consistent with the section 7 actor convention.-  wrongCase <- withStatus "Stable"-  assertEqual (UnknownStatus "Stable") wrongCase-  -- renderStatus inverts readStatus on every value it can read back.-  for_-    [Draft, Stable, Deprecated, UnknownStatus "archived"]-    (\value -> withStatus (renderStatus value) >>= assertEqual value)--testReadStaleAfter :: Either Text ()-testReadStaleAfter = do-  let staleAfterIn source = readStaleAfter . (^. #frontmatter) <$> firstShow (parseDocument source)-  present <- staleAfterIn "---\ntype: Recipe\nstale_after: 2026-09-23\n---\nBody\n"-  assertEqual (Just "2026-09-23") present-  absent <- staleAfterIn "---\ntype: Recipe\n---\nBody\n"-  assertEqual Nothing absent-  -- Read verbatim and not parsed here: a malformed date must survive to be-  -- reported by Okf.Trust.staleness rather than vanish on serialization.-  malformed <- staleAfterIn "---\ntype: Recipe\nstale_after: not-a-date\n---\nBody\n"-  assertEqual (Just "not-a-date") malformed-  let built = setStaleAfter "2026-09-23" (setStatus Deprecated emptyFrontmatter)-  reparsed <- firstShow (parseDocument (serializeDocument (OKFDocument built "# Demo\n")))-  assertEqual (Just "2026-09-23") (readStaleAfter (reparsed ^. #frontmatter))-  assertEqual Deprecated (readStatus (reparsed ^. #frontmatter))--testTrustTier :: Either Text ()-testTrustTier = do-  let verifiedBy actor = Verification (parseActor actor) (Just "2026-06-25T09:00:00Z")-  -- Section 5.3: "No `verified` key => unverified."-  assertEqual Unverified (trustTier [])-  -- "`verified` by non-`human:` actors only => machine-confirmed."-  assertEqual MachineConfirmed (trustTier [verifiedBy "process:finance-nightly"])-  assertEqual MachineConfirmed (trustTier [verifiedBy "reference_agent/gemini-2.5-pro"])-  -- An actor matching none of the three section 7 shapes is still not a human.-  assertEqual MachineConfirmed (trustTier [verifiedBy "something"])-  -- "`verified` by a `human:<id>` actor => human-reviewed", including mixed.-  assertEqual HumanReviewed (trustTier [verifiedBy "human:ahormati"])-  assertEqual-    HumanReviewed-    (trustTier [verifiedBy "process:finance-nightly", verifiedBy "human:ahormati"])-  -- The Ord instance runs lowest to highest, as section 5.3 presents them.-  assertBool "tiers ordered lowest to highest" (Unverified < MachineConfirmed && MachineConfirmed < HumanReviewed)--testLatestVerification :: Either Text ()-testLatestVerification = do-  -- Section 5.2: "'How recently' is the latest `at`."-  assertEqual-    (Just "2026-06-26T02:00:00Z")-    ( latestVerification-        [ Verification (HumanActor "ahormati") (Just "2026-06-25T09:00:00Z"),-          Verification (ProcessActor "finance-nightly") (Just "2026-06-26T02:00:00Z")-        ]-    )-  -- Entries without an `at` are skipped rather than losing the whole result.-  assertEqual-    (Just "2026-06-25T09:00:00Z")-    ( latestVerification-        [ Verification (ProcessActor "nightly") Nothing,-          Verification (HumanActor "ahormati") (Just "2026-06-25T09:00:00Z")-        ]-    )-  assertEqual Nothing (latestVerification [])-  assertEqual Nothing (latestVerification [Verification (HumanActor "ahormati") Nothing])--testStaleness :: Either Text ()-testStaleness = do-  let today = fromGregorian 2026 6 15-  assertEqual NoStaleAfter (staleness today Nothing)-  -- Section 5.5: "A concept is stale when `today >= stale_after`."-  assertEqual (Stale (fromGregorian 2026 6 1)) (staleness today (Just "2026-06-01"))-  -- The boundary: equal to today is stale, not fresh. An off-by-one here is a-  -- real bug, so it is asserted explicitly.-  assertEqual (Stale (fromGregorian 2026 6 15)) (staleness today (Just "2026-06-15"))-  assertEqual Fresh (staleness today (Just "2026-06-16"))-  assertEqual Fresh (staleness today (Just "2026-09-23"))-  -- A malformed deadline is surfaced, never silently treated as fresh.-  assertEqual (StaleAfterUnparseable "not-a-date") (staleness today (Just "not-a-date"))-  assertEqual (StaleAfterUnparseable "2026-13-01") (staleness today (Just "2026-13-01"))-  assertEqual "stale since 2026-06-01" (renderStaleness (staleness today (Just "2026-06-01")))-  assertEqual "ok" (renderStaleness (staleness today (Just "2026-09-23")))---- | A document exercising both usage-window scopes, both credibility-signal--- shapes, a scope-descriptor resource, and an entry missing the one key--- section 5.1 requires within an entry.-sourcesFixtureDocument :: Text-sourcesFixtureDocument =-  Text.unlines-    [ "---",-      "type: BigQuery Table",-      "sources:",-      "  - id: ga4-schema",-      "    resource: https://developers.google.com/analytics/bigquery/export-schema",-      "    title: GA4 BigQuery Export schema",-      "    author: team:ga4-docs",-      "    usage_count: 5000",-      "    last_modified: 2026-05-30",-      "  - id: exec-dash",-      "    resource: dashboards/exec-revenue",-      "    usage_count: 12",-      "    usage_window: { from: 2026-01-01, to: 2026-01-31 }",-      "  - id: broad-scope",-      "    resource: all queries in BigQuery project X",-      "    usage_count: \"5000\"",-      "  - id: no-resource",-      "    title: Missing the required key",-      "usage_window: { from: 2026-06-01, to: 2026-06-30 }",-      "---",-      "",-      "# Orders"-    ]---- | Specification §5.1 makes the footnote label the join key into @sources@, so--- strict validation checks it in both directions: a label naming no entry is a--- defect, and an entry whose id nothing cites is a lint. Neither fires in--- permissive mode, because §11 forbids rejecting a bundle over optional--- frontmatter.-testFootnoteAttributionJoin :: Either Text ()-testFootnoteAttributionJoin = do-  let document mistyped =-        Text.unlines-          [ "---",-            "type: BigQuery Table",-            "title: Orders",-            "description: Order fact table.",-            "generated: { by: okf-agent/1.0, at: 2026-07-31T00:00:00Z }",-            "sources:",-            "  - id: ga4-schema",-            "    resource: https://developers.google.com/analytics/bigquery/export-schema",-            "  - id: uncited-policy",-            "    resource: https://wiki.acme/finance/revenue-recognition",-            "---",-            "",-            "Sharded daily.[^" <> mistyped <> "]",-            "",-            "[^" <> mistyped <> "]: GA4 BigQuery Export schema"-          ]-  mistypedDocument <- firstShow (parseDocument (document "ga4-schmea"))-  assertEqual-    [ FootnoteLabelNotInSources "ga4-schmea",-      SourceIdNotCited "ga4-schema",-      SourceIdNotCited "uncited-policy"-    ]-    (validateDocument StrictAuthoring mistypedDocument)-  assertEqual [] (validateDocument PermissiveConformance mistypedDocument)-  -- Correcting the citation clears the defect and one of the two lints.-  correctedDocument <- firstShow (parseDocument (document "ga4-schema"))-  assertEqual-    [SourceIdNotCited "uncited-policy"]-    (validateDocument StrictAuthoring correctedDocument)---- | Markdown footnotes are ordinary prose used for ordinary purposes. A document--- that has not opted into structured provenance is making no attribution claim,--- so a body full of footnotes must report nothing in either mode.-testFootnoteAttributionSkippedWithoutSources :: Either Text ()-testFootnoteAttributionSkippedWithoutSources = do-  document <--    firstShow-      ( parseDocument-          ( Text.unlines-              [ "---",-                "type: BigQuery Table",-                "title: Orders",-                "description: Order fact table.",-                "generated: { by: okf-agent/1.0, at: 2026-07-31T00:00:00Z }",-                "---",-                "",-                "An aside.[^aside] Another.[^undefined]",-                "",-                "[^aside]: just a footnote, not an attribution"-              ]-          )-      )-  assertEqual [] (validateDocument StrictAuthoring document)-  assertEqual [] (validateDocument PermissiveConformance document)--testReadSources :: Either Text ()-testReadSources = do-  document <- firstShow (parseDocument sourcesFixtureDocument)-  let sources = readSources (document ^. #frontmatter)-  -- The entry with no `resource` is skipped: section 5.1 makes it REQUIRED-  -- within an entry, and reporting it is validation's job, not the reader's.-  assertEqual [Just "ga4-schema", Just "exec-dash", Just "broad-scope"] (map sourceId sources)-  case sources of-    (first_ : _) -> do-      assertEqual "https://developers.google.com/analytics/bigquery/export-schema" (sourceResource first_)-      assertEqual (Just "GA4 BigQuery Export schema") (sourceTitle first_)-      -- `author` uses the section 7 actor convention; `team:ga4-docs` matches-      -- none of the three shapes, so it stays unclassified rather than failing.-      assertEqual (Just (UnclassifiedActor "team:ga4-docs")) (sourceAuthor first_)-      assertEqual (Just 5000) (sourceUsageCount first_)-      assertEqual (Just "2026-05-30") (sourceLastModified first_)-    [] -> Left "expected sources"-  -- Section 5.1 permits a resource to be a population or scope descriptor no-  -- consumer can follow. It must read cleanly and never be treated as a path.-  assertEqual-    (Just "all queries in BigQuery project X")-    (sourceResource <$> List.find ((== Just "broad-scope") . sourceId) sources)-  -- A numeric string is not an integer. Reading it as one would make the-  -- field's type unpredictable and hide a producer mistake.-  assertEqual-    (Just Nothing)-    (sourceUsageCount <$> List.find ((== Just "broad-scope") . sourceId) sources)-  absent <- firstShow (parseDocument "---\ntype: Recipe\n---\nBody\n")-  assertEqual [] (readSources (absent ^. #frontmatter))--testUsageWindowOverride :: Either Text ()-testUsageWindowOverride = do-  document <- firstShow (parseDocument sourcesFixtureDocument)-  let documentWindow = readUsageWindow (document ^. #frontmatter)-      sources = readSources (document ^. #frontmatter)-      windowFor entryId =-        effectiveUsageWindow documentWindow <$> List.find ((== Just entryId) . sourceId) sources-  assertEqual (Just (UsageWindow (Just "2026-06-01") (Just "2026-06-30"))) documentWindow-  -- An entry with no window of its own inherits the document-scope one...-  assertEqual (Just (Just (UsageWindow (Just "2026-06-01") (Just "2026-06-30")))) (windowFor "ga4-schema")-  -- ...and an entry carrying its own overrides it. Two different windows in one-  -- document is the section 5.1 override rule working.-  assertEqual (Just (Just (UsageWindow (Just "2026-01-01") (Just "2026-01-31")))) (windowFor "exec-dash")-  -- With no window at either scope there is nothing to frame a count with.-  noWindow <- firstShow (parseDocument "---\ntype: Recipe\nsources:\n  - resource: https://example.com/a\n---\nBody\n")-  let noWindowSources = readSources (noWindow ^. #frontmatter)-  assertEqual Nothing (readUsageWindow (noWindow ^. #frontmatter))-  assertEqual [Nothing] (effectiveUsageWindow Nothing <$> noWindowSources)--testSourcesRoundTrip :: Either Text ()-testSourcesRoundTrip = do-  let sources =-        [ Source-            { sourceId = Just "ga4-schema",-              sourceResource = "https://developers.google.com/analytics/bigquery/export-schema",-              sourceTitle = Just "GA4 BigQuery Export schema",-              sourceAuthor = Just (parseActor "human:ahormati"),-              sourceUsageCount = Just 5000,-              sourceLastModified = Just "2026-05-30",-              sourceUsageWindow = Nothing-            },-          -- Every optional key absent: these must be omitted on write, not-          -- written as explicit nulls, so the round-trip is lossless.-          Source-            { sourceId = Nothing,-              sourceResource = "all queries in BigQuery project X",-              sourceTitle = Nothing,-              sourceAuthor = Nothing,-              sourceUsageCount = Nothing,-              sourceLastModified = Nothing,-              sourceUsageWindow = Just (UsageWindow (Just "2026-01-01") Nothing)-            }-        ]-      window = UsageWindow (Just "2026-06-01") (Just "2026-06-30")-      built = setUsageWindow window (setSources sources (setType "BigQuery Table" emptyFrontmatter))-  reparsed <- firstShow (parseDocument (serializeDocument (OKFDocument built "# Orders\n")))-  assertEqual sources (readSources (reparsed ^. #frontmatter))-  assertEqual (Just window) (readUsageWindow (reparsed ^. #frontmatter))---- | Specification §10.2's worked example, verbatim. Flow-style mappings and a--- flow-style @receipt@ list are exactly how the specification writes it, which--- is why they are here: a reader that only handles block style would pass a--- hand-normalized fixture and fail on the document an author copied out of §10.-attestedComputationFixtureDocument :: Text-attestedComputationFixtureDocument =-  Text.unlines-    [ "---",-      "type: Attested Computation",-      "title: Revenue for fiscal year",-      "description: Recognized revenue for a fiscal year, per Finance's definition.",-      "status: stable",-      "runtime: bigquery",-      "parameters:",-      "  - { name: year, type: integer, required: true }",-      "executor:",-      "  resource: references/skills/run-on-bq.md",-      "  receipt: [job_id, executed_sql, result]",-      "attester:",-      "  resource: references/attesters/revenue.py",-      "generated: { by: reference_agent/gemini-2.5-pro, at: 2026-06-20T22:53:05Z }",-      "verified: { by: human:ahormati, at: 2026-06-25T09:00:00Z }",-      "stale_after: 2026-09-23",-      "sources:",-      "  - id: rev-policy",-      "    resource: https://wiki.acme/finance/revenue-recognition",-      "    title: Revenue recognition policy",-      "---",-      "",-      "# Computation",-      "",-      "    SELECT SUM(amount) AS revenue FROM finance.recognized_revenue WHERE fiscal_year = @year"-    ]---- | The five §10.2 contract fields read off the specification's own worked--- example. The trust and provenance families in the same frontmatter block are--- asserted too: §10.2 puts them there deliberately, and reading the contract--- must not disturb them.-testReadAttestedComputationContract :: Either Text ()-testReadAttestedComputationContract = do-  document <- firstShow (parseDocument attestedComputationFixtureDocument)-  let frontmatterValue = document ^. #frontmatter-  assertEqual (Just "bigquery") (readRuntime frontmatterValue)-  assertEqual-    [Parameter {parameterName = "year", parameterType = Just "integer", parameterRequired = Just True}]-    (readParameters frontmatterValue)-  -- Absent: §10.3 says an absent `computation` means the body fence is the-  -- computation. Reading the body is a sibling plan's job.-  assertEqual Nothing (readComputation frontmatterValue)-  assertEqual-    ( Just-        Executor-          { executorResource = Just "references/skills/run-on-bq.md",-            executorReceipt = ["job_id", "executed_sql", "result"]-          }-    )-    (readExecutor frontmatterValue)-  assertEqual (Just (Attester (Just "references/attesters/revenue.py"))) (readAttester frontmatterValue)-  -- The §5 families sharing the block still read exactly as before.-  assertEqual-    (Just (Generated (parseActor "reference_agent/gemini-2.5-pro") (Just "2026-06-20T22:53:05Z")))-    (readGenerated frontmatterValue)-  assertEqual [Verification (parseActor "human:ahormati") (Just "2026-06-25T09:00:00Z")] (readVerified frontmatterValue)-  assertEqual Stable (readStatus frontmatterValue)-  assertEqual (Just "2026-09-23") (readStaleAfter frontmatterValue)-  assertEqual [Just "rev-policy"] (map sourceId (readSources frontmatterValue))---- | Every degenerate contract shape yields a value rather than an error.--- Specification §11 forbids rejecting a document for a malformed optional--- field, so the readers are total and reporting is validation's job.-testReadAttestedComputationDegenerateShapes :: Either Text ()-testReadAttestedComputationDegenerateShapes = do-  let readAll source = do-        document <- firstShow (parseDocument source)-        pure (document ^. #frontmatter)-  -- Nothing declared at all.-  bare <- readAll "---\ntype: Attested Computation\n---\nBody\n"-  assertEqual Nothing (readRuntime bare)-  assertEqual [] (readParameters bare)-  assertEqual Nothing (readComputation bare)-  assertEqual Nothing (readExecutor bare)-  assertEqual Nothing (readAttester bare)-  -- `parameters` present but not a list, and `runtime` present but not text.-  wrongShapes <--    readAll-      ( Text.unlines-          [ "---",-            "type: Attested Computation",-            "runtime: { name: bigquery }",-            "parameters: year",-            "computation: [a, b]",-            "---",-            "Body"-          ]-      )-  assertEqual Nothing (readRuntime wrongShapes)-  assertEqual [] (readParameters wrongShapes)-  assertEqual Nothing (readComputation wrongShapes)-  -- An entry with no `name` names no hole and is dropped, exactly as-  -- `readSources` drops an entry with no `resource`. A `required` written as a-  -- string is not a boolean, mirroring `usage_count`'s refusal of "5000".-  partialEntries <--    readAll-      ( Text.unlines-          [ "---",-            "type: Attested Computation",-            "parameters:",-            "  - { type: integer, required: true }",-            "  - { name: year }",-            "  - { name: region, type: string, required: \"true\" }",-            "  - not-a-mapping",-            "---",-            "Body"-          ]-      )-  assertEqual-    [ Parameter {parameterName = "year", parameterType = Nothing, parameterRequired = Nothing},-      Parameter {parameterName = "region", parameterType = Just "string", parameterRequired = Nothing}-    ]-    (readParameters partialEntries)-  -- `executor` as a scalar is not a mapping and is not read; a `receipt`-  -- written as a bare string is read as a one-element list, mirroring how §5.2-  -- tolerates a bare `verified` mapping where a list is expected.-  scalarExecutor <- readAll "---\ntype: Attested Computation\nexecutor: run-on-bq\nattester: revenue.py\n---\nBody\n"-  assertEqual Nothing (readExecutor scalarExecutor)-  assertEqual Nothing (readAttester scalarExecutor)-  bareReceipt <--    readAll-      ( Text.unlines-          [ "---",-            "type: Attested Computation",-            "executor: { receipt: job_id }",-            "attester: { note: no resource here }",-            "---",-            "Body"-          ]-      )-  assertEqual-    (Just Executor {executorResource = Nothing, executorReceipt = ["job_id"]})-    (readExecutor bareReceipt)-  -- An `attester` mapping with no `resource` still reads: "declared badly" and-  -- "not declared" are different facts and only the reader can keep them apart.-  assertEqual (Just (Attester Nothing)) (readAttester bareReceipt)---- | The §10.2 worked example survives serialization losslessly, and the--- normalized form emits the five contract keys in their fixed--- 'coreFrontmatterFieldOrder' position — between the lifecycle @status@ and the--- trust @generated@, which is §10.2's own ordering.------ Byte-identity is asserted against the /normalized/ form rather than against--- the specification's text, because §10.2 writes flow-style mappings that--- 'serializeDocument' expands to block style by design. What this pins is that--- serializing is a fixed point: a bundle regenerated twice yields no diff.-testAttestedComputationRoundTrip :: Either Text ()-testAttestedComputationRoundTrip = do-  document <- firstShow (parseDocument attestedComputationFixtureDocument)-  let normalized = serializeDocument document-  reparsed <- firstShow (parseDocument normalized)-  assertEqual normalized (serializeDocument reparsed)-  -- No contract value was normalized away or rewritten on the way through.-  assertEqual (readRuntime (document ^. #frontmatter)) (readRuntime (reparsed ^. #frontmatter))-  assertEqual (readParameters (document ^. #frontmatter)) (readParameters (reparsed ^. #frontmatter))-  assertEqual (readComputation (document ^. #frontmatter)) (readComputation (reparsed ^. #frontmatter))-  assertEqual (readExecutor (document ^. #frontmatter)) (readExecutor (reparsed ^. #frontmatter))-  assertEqual (readAttester (document ^. #frontmatter)) (readAttester (reparsed ^. #frontmatter))-  assertEqual (body document) (body reparsed)-  assertEqual-    [ "type",-      "title",-      "description",-      "status",-      "runtime",-      "parameters",-      "executor",-      "attester",-      "generated",-      "verified",-      "stale_after",-      "sources"-    ]-    (topLevelKeysInEmissionOrder normalized)---- | §10.3's two forms, read off one document each and then off a document that--- wrongly offers both. The reader restates and never enforces, so the--- both-forms document yields two entries rather than a failure; reporting that--- is 'validateDocument''s job.-testReadComputationSources :: Either Text ()-testReadComputationSources = do-  -- The specification's own worked example: no `computation` key, one indented-  -- block under `# Computation`.-  inline <- firstShow (parseDocument attestedComputationFixtureDocument)-  assertEqual-    [ComputationInline "SELECT SUM(amount) AS revenue FROM finance.recognized_revenue WHERE fiscal_year = @year\n"]-    (readComputationSources inline)-  byFile <--    firstShow-      ( parseDocument-          ( Text.unlines-              [ "---",-                "type: Attested Computation",-                "computation: /references/revenue.sql",-                "---",-                "",-                "# Notes",-                "",-                "The computation lives in a file, so this body carries no block."-              ]-          )-      )-  assertEqual [ComputationFile "/references/revenue.sql"] (readComputationSources byFile)-  both <--    firstShow-      ( parseDocument-          ( Text.unlines-              [ "---",-                "type: Attested Computation",-                "computation: /references/revenue.sql",-                "---",-                "",-                "# Computation",-                "",-                "```sql",-                "SELECT 1",-                "```"-              ]-          )-      )-  assertEqual-    [ComputationFile "/references/revenue.sql", ComputationInline "SELECT 1\n"]-    (readComputationSources both)-  -- Type-agnostic: a `# Computation` section on a `Metric` is still a fact about-  -- that document. Scoping a report to the one type is `Okf.Validation`'s job.-  onMetric <--    firstShow-      ( parseDocument-          (Text.unlines ["---", "type: Metric", "---", "", "# Computation", "", "    SELECT 1"])-      )-  assertEqual [ComputationInline "SELECT 1\n"] (readComputationSources onMetric)---- | The top-level frontmatter keys of a serialized document, in the order they--- were emitted. A top-level key is the only thing that starts in column zero--- inside the frontmatter fence.-topLevelKeysInEmissionOrder :: Text -> [Text]-topLevelKeysInEmissionOrder serialized =-  [ Text.takeWhile (/= ':') line-  | line <- frontmatterLines,-    not (Text.null line),-    Text.isInfixOf ":" line,-    Text.head line /= ' ',-    Text.head line /= '-'-  ]-  where-    frontmatterLines =-      takeWhile (/= "---") (drop 1 (Text.lines serialized))---- | Specification §10.2 marks @runtime@ REQUIRED for @type: Attested--- Computation@, and nothing else in the contract. The check is strict-only:--- §11's conformance list has three items and none is a computation field, and--- §11 separately forbids rejecting a bundle over an unknown @type@ value, so--- "REQUIRED for this type" binds the producer rather than licensing a consumer--- to refuse.-testValidateAttestedComputationRuntime :: Either Text ()-testValidateAttestedComputationRuntime = do-  let errorsFor profile source = validateDocument profile <$> firstShow (parseDocument source)-      concept typeValue extraLines =-        Text.unlines-          ( [ "---",-              "type: " <> typeValue,-              "title: Revenue",-              "description: Recognized revenue for a fiscal year.",-              "generated: { by: human:you, at: 2026-08-01T00:00:00Z }"-            ]-              <> extraLines-              <> ["---", "", "# Computation", "", "    SELECT 1"]-          )-  -- A complete contract is clean under both profiles.-  complete <- errorsFor StrictAuthoring (concept "Attested Computation" ["runtime: bigquery"])-  assertEqual [] complete-  -- No runtime: exactly one problem, and only under strict.-  missing <- errorsFor StrictAuthoring (concept "Attested Computation" [])-  assertEqual [AttestedComputationMissingRuntime] missing-  permissive <- errorsFor PermissiveConformance (concept "Attested Computation" [])-  assertEqual [] permissive-  -- No other type is affected, including a near-miss spelling. §4.1 says types-  -- are not registered centrally and consumers must tolerate unknown ones, so-  -- the match is on the one literal §10.1 names, case-sensitively.-  metric <- errorsFor StrictAuthoring (concept "Metric" [])-  assertEqual [] metric-  nearMiss <- errorsFor StrictAuthoring (concept "attested computation" [])-  assertEqual [] nearMiss-  -- An empty or whitespace runtime declares nothing.-  blank <- errorsFor StrictAuthoring (concept "Attested Computation" ["runtime: \"   \""])-  assertEqual [AttestedComputationMissingRuntime] blank--testValidateSources :: Either Text ()-testValidateSources = do-  let strictErrors source = validateDocument StrictAuthoring <$> firstShow (parseDocument source)-      permissiveErrors source = validateDocument PermissiveConformance <$> firstShow (parseDocument source)-      preamble =-        Text.unlines-          [ "---",-            "type: BigQuery Table",-            "title: Orders",-            "description: Order fact table.",-            "generated: { by: human:ahormati, at: 2026-06-20T22:53:05Z }"-          ]-      broken =-        preamble-          <> Text.unlines-            [ "sources:",-              "  - id: ga4-schema",-              "    resource: https://example.com/ga4",-              "  - id: no-resource",-              "    title: Missing the required key",-              "  - id: ga4-schema",-              "    resource: https://example.com/ga4-again",-              "---",-              "",-              "# Orders"-            ]-  errors <- strictErrors broken-  -- The index is the position in the raw YAML list, which is what a person sees-  -- in the file, not the position in the list readSources returns.-  assertEqual [SourceMissingResource 1, DuplicateSourceId "ga4-schema"] errors-  -- Section 11 forbids rejecting a bundle over an optional family, so neither-  -- diagnostic may fire permissively.-  permissive <- permissiveErrors broken-  assertEqual [] permissive-  -- A well-formed sources list, including a scope-descriptor resource that no-  -- consumer can follow, is clean. Section 5.1 explicitly permits that shape.-  clean <--    strictErrors-      ( preamble-          <> Text.unlines-            [ "sources:",-              "  - id: ga4-schema",-              "    resource: https://example.com/ga4",-              "  - resource: all queries in BigQuery project X",-              "---",-              "",-              "# Orders"-            ]-      )-  assertEqual [] clean-  -- A document with no sources at all stays valid in strict mode.-  noSources <- strictErrors (preamble <> "---\n\n# Orders\n")-  assertEqual [] noSources--testConceptFromDocumentDerivesFields :: Either Text ()-testConceptFromDocumentDerivesFields = do-  conceptId <- parseTestConceptId "tables/orders"-  let frontmatterValue =-        okfCommon-          OkfCommon-            { commonType = "BigQuery Table",-              commonTitle = Just "Orders",-              commonDescription = Nothing,-              commonTimestamp = Nothing-            }-      concept = conceptFromDocument conceptId (OKFDocument frontmatterValue "# Orders\n")-  assertEqual "BigQuery Table" (conceptType concept)-  assertEqual (Just "Orders") (conceptTitle concept)-  assertEqual "tables/orders.md" (conceptSourcePath concept)--testWriteBundleRoundTrip :: IO (Either Text ())-testWriteBundleRoundTrip = do-  temporaryDirectory <- getTemporaryDirectory-  root <- createTempDirectory temporaryDirectory "okf-core-writebundle"-  let buildConcepts = do-        orders <- testConcept "tables/orders" "# Orders\n\nOrder records.\n"-        customers <- testConcept "tables/customers" "# Customers\n\nCustomer records.\n"-        pure [orders, customers]-  case buildConcepts of-    Left message -> do-      removeDirectoryRecursive root-      pure (Left message)-    Right concepts -> do-      writeBundle root concepts-      recovered <- readBundle root-      removeDirectoryRecursive root-      pure-        ( do-            assertEqual-              (List.sort (renderConceptId . conceptIdOf <$> concepts))-              (List.sort (renderConceptId . conceptIdOf <$> recovered))-            assertEqual-              (List.sort ((body . conceptDocument) <$> concepts))-              (List.sort ((body . conceptDocument) <$> recovered))-        )--testFixtureDanglingLink :: IO (Either Text ())-testFixtureDanglingLink = do-  root <- fixturePath "invalid-dangling-link"-  concepts <- readBundle root-  inventory <- readBundleInventory root-  pure-    ( case validateBundle PermissiveConformance VersionUndeclared inventory concepts of-        errs-          | any isDangling errs -> Right ()-          | otherwise -> Left ("expected a DanglingReference, got: " <> Text.pack (show errs))-    )-  where-    isDangling DanglingReference {} = True-    isDangling _ = False---- | The §6.2 path check against a real directory rather than an in-memory--- bundle, which is the only way to exercise the half that needs a filesystem:--- @non-markdown.md@ names @references\/attesters\/revenue.py@, and that resolves--- only because 'walkBundleInventory' sees files 'walkBundle' filters out.------ @computations\/spec-spelling.md@ is the same text written from a--- subdirectory, which is specification §10.2's own spelling and the one shape--- that carries a bundle-relative hint.-testFixtureDanglingFrontmatterPath :: IO (Either Text ())-testFixtureDanglingFrontmatterPath = do-  root <- fixturePath "dangling-frontmatter-path"-  concepts <- readBundle root-  inventory <- readBundleInventory root-  pure-    ( do-        danglingId <- firstShow (parseConceptId "dangling")-        specSpellingId <- firstShow (parseConceptId "computations/spec-spelling")-        assertEqual 4 (length concepts)-        assertEqual-          [ DanglingFrontmatterPath-              specSpellingId-              "resource"-              "computations/references/attesters/revenue.py"-              (Just "references/attesters/revenue.py"),-            DanglingFrontmatterPath danglingId "resource" "references/deleted.txt" Nothing-          ]-          (validateBundle StrictAuthoring (VersionDeclared (OkfVersion 0 2)) inventory concepts)-        assertEqual-          []-          (validateBundle PermissiveConformance (VersionDeclared (OkfVersion 0 2)) inventory concepts)-    )---- | A whole bundle carrying specification §10.2's contract and §10.3's--- exactly-one rule, checked end to end.------ Four things this proves that the document-level tests cannot. The §10.2 and--- §10.3 checks fire on exactly the concepts that get them wrong and leave the--- @Metric@ and the @references\/@ concept alone — @metrics\/revenue@--- carries no computation at all and is reported by none of them, which is what--- proves the checks are keyed on the one @type@. Both of the completed--- computation's path-valued contract fields resolve, including the non-Markdown--- @revenue.py@ — which only works because 'walkBundleInventory' records every--- file rather than only the concepts. @computations\/both-computations@ names a--- @computation@ path that resolves, so its only diagnostic is the §10.3--- ambiguity and not a dangling path. And permissive validation reports nothing--- at all, because §11's conformance list reaches none of this.-testFixtureAttestedComputation :: IO (Either Text ())-testFixtureAttestedComputation = do-  root <- fixturePath "attested-computation"-  concepts <- readBundle root-  inventory <- readBundleInventory root-  pure-    ( do-        marginId <- firstShow (parseConceptId "computations/margin")-        revenueId <- firstShow (parseConceptId "computations/revenue")-        bothId <- firstShow (parseConceptId "computations/both-computations")-        noneId <- firstShow (parseConceptId "computations/no-computation")-        twoBlocksId <- firstShow (parseConceptId "computations/two-blocks")-        -- Six computations, one metric, and the one `references/` file that-        -- `walkBundle` treats as a concept because it is non-reserved Markdown.-        -- The `.py` and `.sql` under `references/` are files and not concepts.-        ---        -- The sixth computation, `computations/churn`, deliberately produces no-        -- diagnostic here. It is core-clean and deviates only from the house-        -- profile in `profiles/attested-computation-house.dhall`, which is what-        -- makes this bundle exercise both layers rather than only this one.-        assertEqual 8 (length concepts)-        assertEqual-          [ DocumentInvalid bothId AttestedComputationHasBothComputations,-            DocumentInvalid marginId AttestedComputationMissingRuntime,-            DocumentInvalid noneId AttestedComputationHasNoComputation,-            DocumentInvalid twoBlocksId (AttestedComputationHasManyBlocks 2)-          ]-          (validateBundle StrictAuthoring (VersionDeclared (OkfVersion 0 2)) inventory concepts)-        assertEqual-          []-          (validateBundle PermissiveConformance (VersionDeclared (OkfVersion 0 2)) inventory concepts)-        -- The contract projected onto the concept, which is what every command-        -- reads rather than reaching back into raw frontmatter.-        revenue <- maybe (Left "expected computations/revenue") Right (findConcept revenueId concepts)-        assertEqual (Just "bigquery") (conceptRuntime revenue)-        assertEqual ["year"] (parameterName <$> conceptParameters revenue)-        assertEqual Nothing (conceptComputation revenue)-        assertEqual-          (Just "/references/skills/run-on-bq.md")-          (executorResource =<< conceptExecutor revenue)-        assertEqual (Just ["job_id", "executed_sql", "result"]) (executorReceipt <$> conceptExecutor revenue)-        assertEqual (Just "/references/attesters/revenue.py") (attesterResource =<< conceptAttester revenue)-        -- The body half of §10.3, projected alongside the frontmatter half: this-        -- concept names no `computation` path, so its one computation is the-        -- indented block under `# Computation`.-        assertEqual-          [ ComputationInline-              "SELECT SUM(amount) AS revenue\nFROM finance.recognized_revenue\nWHERE fiscal_year = @year\n"-          ]-          (conceptComputationSources revenue)-    )---- | Resolve a fixture file path regardless of whether tests run from the repo--- root or the package directory (mirrors 'fixturePath' for files).-fixtureFilePath :: FilePath -> IO FilePath-fixtureFilePath name = findExisting candidates-  where-    candidates =-      [ "okf-core" </> "test" </> "fixtures" </> name,-        "test" </> "fixtures" </> name-      ]-    findExisting [] = fail ("fixture file not found: " <> name)-    findExisting (candidate : rest) = do-      exists <- doesFileExist candidate-      if exists then pure candidate else findExisting rest---- | Milestone 1: the Dhall descriptor round-trips into a 'ProfileSpec'.-testLoadProfileFixture :: IO (Either Text ())-testLoadProfileFixture = do-  path <- fixtureFilePath "profiles/postgresql.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load profile: " <> err)-    Right spec -> do-      assertEqual "shinzui-postgresql" (spec ^. #name)-      assertEqual-        (Just "Conventions for documenting a PostgreSQL database as an OKF bundle.")-        (spec ^. #description)-      assertEqual False (spec ^. #allowUnknownTypes)-      assertEqual ["type", "title"] (map (^. #field) (spec ^. #frontmatter . #required))-      assertEqual-        [ Just "The OKF concept type; must be one of the type rules below.",-          Just "Human-readable name of the object, as a reader would say it."-        ]-        (map (^. #description) (spec ^. #frontmatter . #required))-      -- `timestamp` is written with bare record completion, so it carries no prose.-      assertEqual-        [ Just "One or two sentences on what this object is for.",-          Nothing,-          Just "postgresql:// URI locating the live object."-        ]-        (map (^. #description) (spec ^. #frontmatter . #recommended))-      assertEqual-        ["PostgreSQL Schema", "PostgreSQL Table", "PostgreSQL View"]-        (map (^. #type_) (spec ^. #types))-      assertEqual-        (Just "One physical table in a schema, including its column list.")-        (spec ^. #types . to (!! 1) . #description)--testLoadDocumentIdProfileFixture :: IO (Either Text ())-testLoadDocumentIdProfileFixture = do-  path <- fixtureFilePath "profiles/decisions.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load document ID profile: " <> err)-    Right spec -> do-      assertEqual (Just "docId") (spec ^. #idField)-      assertEqual [Just "ADR"] (map (^. #idPrefix) (spec ^. #types))-      -- Written with the mk/FieldRule.dhall constructors, which normalize to-      -- exactly what record completion produces.-      assertEqual ["type", "title"] (map (^. #field) (spec ^. #frontmatter . #required))-      assertEqual-        [Just "The OKF concept type; must be a type rule below.", Nothing]-        (map (^. #description) (spec ^. #frontmatter . #required))--testLoadNestedReferenceProfileFixture :: IO (Either Text ())-testLoadNestedReferenceProfileFixture = do-  path <- fixtureFilePath "profiles/nested-references-and-uniqueness.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load nested reference profile: " <> err)-    Right spec -> do-      dependencies <- lookupRawRule "dependencies" (spec ^. #frontmatter . #required)-      acceptanceCriteria <- lookupRawRule "acceptanceCriteria" (spec ^. #frontmatter . #required)-      assertEqual (Just "id") (acceptanceCriteria ^. #uniqueBy)-      case dependencies ^. #elementFields of-        Just NestedRules {required = [nestedReferenceRule]} -> do-          let expectedPolicy =-                HandleReferenceRule-                  "IR"-                  ["mori"]-                  False-                  False-                  (Just "mori://[^/]+/[^/]+/okf/improvement-requests/concepts/IR-[1-9][0-9]*")-          assertEqual (Just expectedPolicy) (nestedReferenceRule ^. #reference)-          assertEqual-            ( object-                [ "field" .= ("ref" :: Text),-                  "description" .= (Nothing :: Maybe Text),-                  "allowedValues" .= ([] :: [Text]),-                  "cardinality" .= ("scalar" :: Text),-                  "format" .= (Nothing :: Maybe Text),-                  "when" .= (Nothing :: Maybe FieldCondition),-                  "path" .= (Nothing :: Maybe PathReferenceRule),-                  "reference" .= Just expectedPolicy-                ]-            )-            (toJSON nestedReferenceRule)-        _ -> Left "expected dependencies.ref as one required nested rule"-  where-    lookupRawRule key rules =-      case [rule | rule <- rules, rule ^. #field == key] of-        [rule] -> Right rule-        _ -> Left ("expected one raw rule for " <> key)--testLoadDescribedProfileFixture :: IO (Either Text ())-testLoadDescribedProfileFixture = do-  path <- fixtureFilePath "profiles/described.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load described profile: " <> err)-    Right spec -> do-      assertEqual "described" (spec ^. #name)-      assertEqual ["Described Concept"] (map (^. #type_) (spec ^. #types))-      assertEqual [emptyTestFrontmatterRules] (map (^. #frontmatter) (spec ^. #types))-      assertEqual True (spec ^. #allowUnknownFields)-      assertEqual [[]] (map (^. #allowedValues) (spec ^. #frontmatter . #required))-      assertEqual [Any] (map (^. #cardinality) (spec ^. #frontmatter . #required))--testLoadTypeAwareCompatibilityFixture :: IO (Either Text ())-testLoadTypeAwareCompatibilityFixture = do-  path <- fixtureFilePath "profiles/type-aware-ep1.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load EP-1 profile: " <> err)-    Right spec -> do-      assertEqual "type-aware-ep1" (spec ^. #name)-      assertEqual True (spec ^. #allowUnknownFields)-      assertEqual [[]] (map (^. #allowedValues) (spec ^. #frontmatter . #required))-      assertEqual [[[]]] (map (map (^. #allowedValues) . (^. #frontmatter . #required)) (spec ^. #types))-      assertEqual [Any] (map (^. #cardinality) (spec ^. #frontmatter . #required))--testLoadVocabularyCompatibilityFixture :: IO (Either Text ())-testLoadVocabularyCompatibilityFixture = do-  path <- fixtureFilePath "profiles/vocabulary-ep2.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load EP-2 profile: " <> err)-    Right spec -> do-      assertEqual "vocabulary-ep2" (spec ^. #name)-      assertEqual False (spec ^. #allowUnknownFields)-      assertEqual [[], ["draft", "accepted"]] (map (^. #allowedValues) (spec ^. #frontmatter . #required))-      assertEqual [Any, Any] (map (^. #cardinality) (spec ^. #frontmatter . #required))-      assertEqual [Nothing, Nothing] (map (^. #format) (spec ^. #frontmatter . #required))--testLoadCardinalityCompatibilityFixture :: IO (Either Text ())-testLoadCardinalityCompatibilityFixture = do-  path <- fixtureFilePath "profiles/cardinality-ep3.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load EP-3 profile: " <> err)-    Right spec -> do-      assertEqual "cardinality-ep3" (spec ^. #name)-      assertEqual False (spec ^. #allowUnknownFields)-      assertEqual [Any, Scalar] (map (^. #cardinality) (spec ^. #frontmatter . #required))-      assertEqual [Nothing, Nothing] (map (^. #format) (spec ^. #frontmatter . #required))--testLoadFormatCompatibilityFixture :: IO (Either Text ())-testLoadFormatCompatibilityFixture = do-  path <- fixtureFilePath "profiles/formats-ep4.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load EP-4 profile: " <> err)-    Right spec -> do-      assertEqual "formats-ep4" (spec ^. #name)-      assertEqual [Any, Scalar] (map (^. #cardinality) (spec ^. #frontmatter . #required))-      assertEqual [Nothing, Just Rfc3339Utc] (map (^. #format) (spec ^. #frontmatter . #required))-      assertEqual [Nothing, Nothing] (map (^. #elementFields) (spec ^. #frontmatter . #required))--testLoadNestedReviewsProfileFixture :: IO (Either Text ())-testLoadNestedReviewsProfileFixture = do-  path <- fixtureFilePath "profiles/nested-reviews.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load nested review profile: " <> err)-    Right spec ->-      case [rules | rule <- spec ^. #frontmatter . #required, rule ^. #field == "reviews", Just rules <- [rule ^. #elementFields]] of-        [NestedRules {required, recommended}] -> do-          assertEqual ["kind", "reviewer", "reviewed_at", "document_timestamp", "scope", "outcome", "context"] (map (^. #field) required)-          assertEqual ["notes"] (map (^. #field) recommended)-        _ -> Left "expected exactly one reviews rule with elementFields"--testLoadNestedCompatibilityFixture :: IO (Either Text ())-testLoadNestedCompatibilityFixture = do-  path <- fixtureFilePath "profiles/nested-reviews-ep1.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load frozen nested profile: " <> err)-    Right spec ->-      case spec ^. #frontmatter . #required of-        [rule] -> do-          assertEqual Nothing (rule ^. #when)-          case rule ^. #elementFields of-            Just NestedRules {required = [nestedRule]} -> do-              assertEqual "kind" (nestedRule ^. #field)-              assertEqual Nothing (nestedRule ^. #when)-            _ -> Left "expected the frozen nested rule to survive the compatibility upgrade"-        _ -> Left "expected one frozen top-level rule"--testLoadConditionalFieldsProfileFixture :: IO (Either Text ())-testLoadConditionalFieldsProfileFixture = do-  path <- fixtureFilePath "profiles/conditional-fields.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load conditional profile: " <> err)-    Right spec -> do-      assertEqual "conditional-fields" (spec ^. #name)-      compiled <- firstShow (compileProfile spec)-      assertEqual spec (compiledProfileSpec compiled)--testLoadConditionalCompatibilityFixture :: IO (Either Text ())-testLoadConditionalCompatibilityFixture = do-  path <- fixtureFilePath "profiles/conditional-fields-ep2.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load frozen condition-aware profile: " <> err)-    Right spec ->-      case spec ^. #frontmatter . #required of-        [sourceRule, targetRule, reviewsRule] -> do-          assertEqual Nothing (sourceRule ^. #reference)-          assertEqual (Just (FieldCondition "status" ["superseded"])) (targetRule ^. #when)-          assertEqual Nothing (targetRule ^. #reference)-          case reviewsRule ^. #elementFields of-            Just NestedRules {required = [_kindRule, providerRule]} ->-              assertEqual (Just (FieldCondition "kind" ["model"])) (providerRule ^. #when)-            _ -> Left "expected frozen nested conditions to survive the compatibility upgrade"-        _ -> Left "expected three frozen condition-aware top-level rules"---- | The immediately preceding generation: a descriptor that spells out the--- reference-aware record types with no @optional@ list anywhere still loads,--- keeps every field it did declare, and behaves as though each optional list--- were empty.-testLoadReferenceCompatibilityFixture :: IO (Either Text ())-testLoadReferenceCompatibilityFixture = do-  path <- fixtureFilePath "profiles/document-references-ep3.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load frozen reference-aware profile: " <> err)-    Right spec -> do-      assertEqual [] (spec ^. #frontmatter . #optional)-      assertEqual [[]] (map (^. #frontmatter . #optional) (spec ^. #types))-      case spec ^. #frontmatter . #recommended of-        [referenceRule, conditionRule, reviewsRule] -> do-          assertEqual-            (Just (handleReferenceRule "ADR" ["mori"] False))-            (referenceRule ^. #reference)-          assertEqual (Just (FieldCondition "status" ["superseded"])) (conditionRule ^. #when)-          case reviewsRule ^. #elementFields of-            Just NestedRules {required = [kindRule], recommended = [notesRule], optional = nestedOptional} -> do-              assertEqual "kind" (kindRule ^. #field)-              assertEqual "notes" (notesRule ^. #field)-              assertEqual [] (map (^. #field) nestedOptional)-            _ -> Left "expected the frozen nested rules to survive with an empty optional list"-        _ -> Left "expected three frozen reference-aware recommended rules"---- | Every frozen generation fixture must both decode /and/ compile.------ Decoding alone is the weaker property and was, until this test, the only one--- asserted: eight of the nine generation tests stopped at 'loadProfileFile'. But--- the guarantee the frozen chain exists to provide is that a descriptor pinned--- at any released version keeps /working/, and between decoding and working sits--- 'compileProfile' — where every 'ProfileDefinitionError' is a way for a--- descriptor that decoded perfectly to stop working.------ The gap was not theoretical. A compile-time version check written for this--- plan rejected ten fixtures at once, and the failures surfaced in unrelated--- documentation and optional-field tests rather than here, which is a far worse--- signal. It also let @path-references-mp8-ep3.dhall@ ship in a state where it--- decoded and could never compile. See--- @docs\/adr\/11-growing-the-profile-descriptor-language.md@.-testFrozenFixturesCompile :: IO (Either Text ())-testFrozenFixturesCompile = do-  results <- traverse loadAndCompile frozenGenerationFixtures-  pure (sequence_ results)-  where-    loadAndCompile name = do-      path <- fixtureFilePath ("profiles/" <> name)-      result <- loadProfileFile path-      pure $ case result of-        Left err -> Left (Text.pack name <> " failed to load: " <> err)-        Right spec ->-          case compileProfile spec of-            Left definitionErrors ->-              Left (Text.pack name <> " loads but does not compile: " <> Text.pack (show (toList definitionErrors)))-            Right _ -> Right ()---- | The fixtures that stand for a released descriptor generation, and so must--- represent something a real pinned descriptor could be.------ The @*-invalid.dhall@ fixtures are deliberately excluded: they exist to prove--- a definition error fires. @document-references-ep3.dhall@ is excluded for a--- different and less happy reason — it declares a profile-scope @when@ condition--- on @status@ while declaring @status@ only at type scope, so it decodes and has--- never compiled. That is the same latent defect this test exists to prevent,--- predating it, and repairing it means changing which rules the fixture declares,--- which its own test asserts. It is recorded in--- @docs\/plans\/47-enforce-the-profile-declared-okfversion-and-ship-a-v0-2-reference-profile.md@--- rather than fixed speculatively here.-frozenGenerationFixtures :: [FilePath]-frozenGenerationFixtures =-  [ "legacy-0.2.dhall",-    "described.dhall",-    "type-aware-ep1.dhall",-    "vocabulary-ep2.dhall",-    "cardinality-ep3.dhall",-    "formats-ep4.dhall",-    "nested-reviews-ep1.dhall",-    "conditional-fields-ep2.dhall",-    "object-fields-mp8-ep1.dhall",-    "formats-mp8-ep2.dhall",-    "path-references-mp8-ep3.dhall",-    "pre-bundle-version.dhall",-    "pre-nested-references-and-uniqueness-0.7.0.0.dhall",-    "pre-guidance-0.8.0.0.dhall",-    -- Not a frozen generation but a *documented* one: this is the descriptor-    -- @docs\/user\/profiles.md@ shows for the specification §10 contract as a-    -- house convention. It is listed here so the documented descriptor cannot-    -- rot into something that no longer compiles.-    "attested-computation-house.dhall"-  ]---- | The complete okf-core 0.8.0.0 descriptor generation predates guidance.--- Both explicit file loading and registry enumeration must reach the same newest--- frozen decoder, preserve every old value, attach absent guidance at both--- scopes, and leave the upgraded profile compilable.-testLoadPreGuidanceCompatibilityFixture :: IO (Either Text ())-testLoadPreGuidanceCompatibilityFixture = do-  path <- fixtureFilePath "profiles/pre-guidance-0.8.0.0.dhall"-  loaded <- loadProfileFile path-  registered <- loadRegistry (RegistryFile path)-  pure $ do-    spec <- first ("failed to load frozen pre-guidance profile: " <>) loaded-    assertEqual "pre-guidance-0.8.0.0" (spec ^. #name)-    assertEqual (Just "The complete public 0.8.0.0 descriptor shape.") (spec ^. #description)-    assertEqual Nothing (spec ^. #guidance)-    assertEqual "0.2" (spec ^. #okfVersion)-    assertEqual False (spec ^. #allowUnknownTypes)-    assertEqual True (spec ^. #allowUnknownFields)-    assertEqual (Just "docId") (spec ^. #idField)-    assertEqual (Just "0.2") (spec ^. #requireBundleVersion)-    assertEqual ["type", "dependencies", "generated"] (map (^. #field) (spec ^. #frontmatter . #required))-    assertEqual [Just Profile.NonNegativeInteger] (map (^. #format) (spec ^. #frontmatter . #recommended))-    assertEqual [Just "METRIC"] (map (^. #idPrefix) (spec ^. #types))-    assertEqual [Nothing] (map (^. #guidance) (spec ^. #types))-    case spec ^. #frontmatter . #required of-      [_typeRule, dependenciesRule, generatedRule] -> do-        assertEqual (Just "id") (dependenciesRule ^. #uniqueBy)-        case dependenciesRule ^. #elementFields of-          Just NestedRules {optional = [refRule]} ->-            assertEqual-              (Just (HandleReferenceRule "METRIC" ["mori"] False False (Just "mori://shinzui/.+")))-              (refRule ^. #reference)-          _ -> Left "expected the frozen nested reference rule to survive"-        case generatedRule ^. #objectFields of-          Just NestedRules {required = [_byRule, atRule]} ->-            assertEqual (Just Rfc3339Utc) (atRule ^. #format)-          _ -> Left "expected the frozen object rules to survive"-      _ -> Left "expected three frozen required rules"-    _ <- first (Text.pack . show . toList) (compileProfile spec)-    entries <- first ("failed to enumerate frozen pre-guidance profile: " <>) registered-    assertEqual [""] (map (^. #export) entries)-    assertEqual ["pre-guidance-0.8.0.0"] (map (^. #spec . #name) entries)-    assertEqual [Nothing] (map (^. #spec . #guidance) entries)-    registrySpec <- case entries of-      [entry] -> Right (entry ^. #spec)-      _ -> Left "expected exactly one frozen pre-guidance registry entry"-    assertEqual-      [Just "id"]-      [ rule ^. #uniqueBy-      | rule <- registrySpec ^. #frontmatter . #required,-        rule ^. #field == "dependencies"-      ]-    case [ nestedRule ^. #reference-         | rule <- registrySpec ^. #frontmatter . #required,-           rule ^. #field == "dependencies",-           rules <- maybeToList (rule ^. #elementFields),-           nestedRule <- rules ^. #optional-         ] of-      [Just policy] -> assertEqual False (policy ^. #allowLocal)-      _ -> Left "expected registry decoding to preserve the nested reference policy"---- | Guidance is free-form authoring prose, so decoding and JSON must preserve--- line breaks rather than folding it into a single display line. The Dhall--- multiline syntax contributes a final newline; that byte is part of the value--- and therefore part of this compatibility contract too.-testLoadGuidanceFixture :: IO (Either Text ())-testLoadGuidanceFixture = do-  path <- fixtureFilePath "profiles/guidance.dhall"-  loaded <- loadProfileFile path-  pure $ do-    spec <- first ("failed to load guidance profile: " <>) loaded-    let expectedProfileGuidance =-          "Record the setup, cleanup, and evidence for every run.\n\nKeep supporting checks in source control and make the observed result reproducible.\n"-        expectedTypeGuidance =-          [ "Add a source-controlled Hurl file that exercises the successful response and important failure responses.\n\nRun the Hurl file and retain the useful output as evidence.\n",-            "Exercise the public behavior, then inspect the generated domain-event stream.\n\nVerify event types, payloads, ordering, and stream identity, then verify the externally observable result.\n"-          ]-    assertEqual (Just expectedProfileGuidance) (spec ^. #guidance)-    assertEqual (map Just expectedTypeGuidance) (map (^. #guidance) (spec ^. #types))-    assertJsonGuidance expectedProfileGuidance (toJSON spec)-    for_ (zip expectedTypeGuidance (spec ^. #types)) $ \(expected, rule) ->-      assertJsonGuidance expected (toJSON rule)-  where-    assertJsonGuidance expected = \case-      Aeson.Object fields ->-        assertEqual (Just (Aeson.String expected)) (KeyMap.lookup "guidance" fields)-      _ -> Left "expected profile JSON to be an object"---- | Guidance is deliberately outside compilation and validation. Removing all--- guidance from a descriptor must not change either permissive or strict--- diagnostics for the same concepts.-testGuidanceDoesNotAffectValidation :: IO (Either Text ())-testGuidanceDoesNotAffectValidation = do-  path <- fixtureFilePath "profiles/guidance.dhall"-  loaded <- loadProfileFile path-  let conceptResult = profileConcept "guidance-inert" [] "# Guidance inertness\n"-  pure $ do-    spec <- first ("failed to load guidance profile: " <>) loaded-    concept <- conceptResult-    guided <- firstShow (compileProfile spec)-    let unguidedSpec =-          spec-            & #guidance-            .~ Nothing-            & #types-            %~ map clearTypeGuidance-    unguided <- firstShow (compileProfile unguidedSpec)-    assertEqual-      (validateProfile PermissiveConformance unguided [concept])-      (validateProfile PermissiveConformance guided [concept])-    assertEqual-      (validateProfile StrictAuthoring unguided [concept])-      (validateProfile StrictAuthoring guided [concept])-  where-    clearTypeGuidance :: TypeRule -> TypeRule-    clearTypeGuidance rule = rule & #guidance .~ Nothing--testLoadPreNestedReferenceCompatibilityFixture :: IO (Either Text ())-testLoadPreNestedReferenceCompatibilityFixture = do-  path <- fixtureFilePath "profiles/pre-nested-references-and-uniqueness-0.7.0.0.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load frozen 0.7.0.0 profile: " <> err)-    Right spec -> do-      assertEqual "pre-nested-references-and-uniqueness-0.7.0.0" (spec ^. #name)-      assertEqual (Just "0.2") (spec ^. #requireBundleVersion)-      let allTopRules = spec ^. #frontmatter . #required <> spec ^. #frontmatter . #recommended <> spec ^. #frontmatter . #optional-      assertEqual (replicate (length allTopRules) Nothing) (map (^. #uniqueBy) allTopRules)-      case [policy | rule <- allTopRules, Just policy <- [rule ^. #reference]] of-        [policy] -> do-          assertEqual True (policy ^. #allowLocal)-          assertEqual Nothing (policy ^. #externalUriPattern)-        _ -> Left "expected exactly one upgraded 0.7.0.0 reference policy"-      let nestedRules =-            [ nestedRule-            | rule <- allTopRules,-              rules <- catMaybes [rule ^. #elementFields, rule ^. #objectFields],-              nestedRule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional-            ]-      assertEqual (replicate (length nestedRules) Nothing) (map (^. #reference) nestedRules)---- | The generation frozen immediately before @requireBundleVersion@: a descriptor--- with no such member still loads, the member arrives as 'Nothing', and every--- member the frozen descriptor did declare survives the upgrade. The last part is--- what would catch an upgrade function that dropped a field while adding the new--- one, which is the failure mode a chain this long invites.-testLoadPreBundleVersionCompatibilityFixture :: IO (Either Text ())-testLoadPreBundleVersionCompatibilityFixture = do-  path <- fixtureFilePath "profiles/pre-bundle-version.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load frozen pre-bundle-version profile: " <> err)-    Right spec -> do-      assertEqual "pre-bundle-version" (spec ^. #name)-      -- The new member, absent from the descriptor, means "demand nothing".-      assertEqual Nothing (spec ^. #requireBundleVersion)-      -- Everything else survived: prose, settings, and rules at both scopes.-      assertEqual (Just "Frozen immediately before requireBundleVersion.") (spec ^. #description)-      assertEqual "0.2" (spec ^. #okfVersion)-      assertEqual False (spec ^. #allowUnknownTypes)-      assertEqual True (spec ^. #allowUnknownFields)-      assertEqual (Just "docId") (spec ^. #idField)-      assertEqual ["type", "generated"] (map (^. #field) (spec ^. #frontmatter . #required))-      assertEqual-        (Just (handleReferenceRule "ADR" ["mori"] False))-        (case spec ^. #frontmatter . #optional of rule : _ -> rule ^. #reference; [] -> Nothing)-      assertEqual-        [Just Profile.HumanActor]-        (concatMap (map (^. #format) . (^. #frontmatter . #required)) (spec ^. #types))-      assertEqual [Just "ADR"] (map (^. #idPrefix) (spec ^. #types))---- | The generation frozen immediately before path-valued reference rules: a--- descriptor with no @path@ member on 'FieldRule' or 'NestedFieldRule' still--- loads, every member it did declare survives at both levels and at both nested--- shapes, and the new member arrives as 'Nothing' everywhere. The fixture writes--- out every published type it names, unions included, so widening one cannot--- quietly turn this into a test of the current decoder.-testLoadPrePathCompatibilityFixture :: IO (Either Text ())-testLoadPrePathCompatibilityFixture = do-  path <- fixtureFilePath "profiles/path-references-mp8-ep3.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load frozen pre-path profile: " <> err)-    Right spec -> do-      assertEqual "path-references-mp8-ep3" (spec ^. #name)-      -- The new member is absent everywhere it can appear: three top-level-      -- presence lists, one type scope, and both nested shapes.-      assertEqual [Nothing, Nothing, Nothing] (map (^. #path) (spec ^. #frontmatter . #required))-      assertEqual [Nothing] (map (^. #path) (spec ^. #frontmatter . #recommended))-      assertEqual [Nothing] (map (^. #path) (spec ^. #frontmatter . #optional))-      assertEqual-        [Nothing]-        (concatMap (map (^. #path) . (^. #frontmatter . #required)) (spec ^. #types))-      -- Everything the frozen descriptor did declare survives the upgrade.-      assertEqual-        (Just (handleReferenceRule "ADR" ["mori"] False))-        (case spec ^. #frontmatter . #optional of rule : _ -> rule ^. #reference; [] -> Nothing)-      assertEqual-        [Just Profile.NonNegativeInteger]-        (map (^. #format) (spec ^. #frontmatter . #recommended))-      assertEqual-        [Just Profile.HumanActor]-        (concatMap (map (^. #format) . (^. #frontmatter . #required)) (spec ^. #types))-      case spec ^. #frontmatter . #required of-        [_typeRule, sourcesRule, generatedRule] -> do-          case sourcesRule ^. #elementFields of-            Just NestedRules {required = [resourceRule]} -> do-              assertEqual "resource" (resourceRule ^. #field)-              assertEqual Scalar (resourceRule ^. #cardinality)-              assertEqual Nothing (resourceRule ^. #path)-            _ -> Left "expected the frozen element-field rule to survive"-          case generatedRule ^. #objectFields of-            Just NestedRules {required = [byRule]} -> do-              assertEqual "by" (byRule ^. #field)-              assertEqual (Just Profile.Actor) (byRule ^. #format)-              assertEqual Nothing (byRule ^. #path)-            _ -> Left "expected the frozen object-member rule to survive"-        _ -> Left "expected three frozen required rules"---- | The generation frozen immediately before the OKF v0.2 value formats: a--- descriptor whose records match today's shape but whose @format@ members are--- typed by the five-alternative format union still loads, and every format it--- declared arrives as the corresponding current 'FieldFormat'. The fixture--- writes the union out as a literal rather than importing--- @okf-core\/dhall\/FieldFormat.dhall@, so widening that file cannot quietly--- turn this into a test of the current decoder.-testLoadPreActorCompatibilityFixture :: IO (Either Text ())-testLoadPreActorCompatibilityFixture = do-  path <- fixtureFilePath "profiles/formats-mp8-ep2.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load frozen five-alternative format profile: " <> err)-    Right spec -> do-      assertEqual "formats-mp8-ep2" (spec ^. #name)-      assertEqual-        [Nothing, Nothing, Nothing]-        (map (^. #format) (spec ^. #frontmatter . #required))-      assertEqual-        [Just Rfc3339Utc, Just Date]-        (map (^. #format) (spec ^. #frontmatter . #recommended))-      assertEqual-        [Just (UriWithScheme "https"), Just (DocumentHandle "ADR"), Just Uri]-        (map (^. #format) (spec ^. #frontmatter . #optional))-      assertEqual-        [Just Date]-        (concatMap (map (^. #format) . (^. #frontmatter . #required)) (spec ^. #types))-      case spec ^. #frontmatter . #required of-        [_typeRule, _titleRule, generatedRule] ->-          case generatedRule ^. #objectFields of-            Just NestedRules {required = [byRule, atRule]} -> do-              assertEqual "by" (byRule ^. #field)-              assertEqual Nothing (byRule ^. #format)-              assertEqual (Just Rfc3339Utc) (atRule ^. #format)-            _ -> Left "expected the frozen object members to survive"-        _ -> Left "expected three frozen required rules"---- | The generation frozen immediately before object rules: a descriptor that--- spells out the optional-presence record types with no @objectFields@ member--- anywhere still loads, keeps every field it did declare — including the--- @optional@ lists at both scopes and one level of @elementFields@ — and--- behaves as though every rule declared no object shape.-testLoadPreObjectCompatibilityFixture :: IO (Either Text ())-testLoadPreObjectCompatibilityFixture = do-  path <- fixtureFilePath "profiles/object-fields-mp8-ep1.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load frozen optional-presence profile: " <> err)-    Right spec -> do-      assertEqual "object-fields-mp8-ep1" (spec ^. #name)-      assertEqual-        [Nothing, Nothing]-        (map (^. #objectFields) (spec ^. #frontmatter . #required))-      assertEqual-        [Nothing, Nothing]-        (map (^. #objectFields) (spec ^. #frontmatter . #recommended))-      assertEqual ["supersededBy"] (map (^. #field) (spec ^. #frontmatter . #optional))-      assertEqual [Nothing] (map (^. #objectFields) (spec ^. #frontmatter . #optional))-      case spec ^. #frontmatter . #recommended of-        [referenceRule, reviewsRule] -> do-          assertEqual-            (Just (handleReferenceRule "ADR" ["mori"] False))-            (referenceRule ^. #reference)-          case reviewsRule ^. #elementFields of-            Just NestedRules {required = [kindRule], recommended = [notesRule], optional = [urlRule]} -> do-              assertEqual "kind" (kindRule ^. #field)-              assertEqual "notes" (notesRule ^. #field)-              assertEqual "url" (urlRule ^. #field)-            _ -> Left "expected the frozen nested rules to survive with all three presence lists"-        _ -> Left "expected two frozen optional-presence recommended rules"---- | The backwards-compatibility guarantee: a descriptor frozen in the okf 0.2.x--- shape — bare-string frontmatter keys, no descriptions anywhere — still loads,--- via the legacy fallback decoder, with every description absent.-testLoadLegacyProfileFixture :: IO (Either Text ())-testLoadLegacyProfileFixture = do-  path <- fixtureFilePath "profiles/legacy-0.2.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load legacy profile: " <> err)-    Right spec -> do-      assertEqual "legacy" (spec ^. #name)-      assertEqual Nothing (spec ^. #description)-      assertEqual Nothing (spec ^. #guidance)-      assertEqual ["type", "title"] (map (^. #field) (spec ^. #frontmatter . #required))-      assertEqual [Nothing, Nothing] (map (^. #description) (spec ^. #frontmatter . #required))-      assertEqual ["Legacy Concept"] (map (^. #type_) (spec ^. #types))-      assertEqual [Nothing] (map (^. #description) (spec ^. #types))-      assertEqual [Nothing] (map (^. #guidance) (spec ^. #types))-      assertEqual True (spec ^. #allowUnknownFields)-      assertEqual [[], []] (map (^. #allowedValues) (spec ^. #frontmatter . #required))-      assertEqual [Any, Any] (map (^. #cardinality) (spec ^. #frontmatter . #required))--testProfileFieldDescription :: IO (Either Text ())-testProfileFieldDescription = do-  path <- fixtureFilePath "profiles/postgresql.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load profile: " <> err)-    Right spec -> do-      assertEqual-        (Just "Human-readable name of the object, as a reader would say it.")-        (profileFieldDescription spec "title")-      assertEqual-        (Just "postgresql:// URI locating the live object.")-        (profileFieldDescription spec "resource")-      assertEqual Nothing (profileFieldDescription spec "timestamp")-      assertEqual Nothing (profileFieldDescription spec "nope")---- | Prose declared on an optional rule is as discoverable as prose on a required--- or recommended one; the third list is searched last, after the two that can--- produce a missing-field diagnostic.-testOptionalFieldDescription :: IO (Either Text ())-testOptionalFieldDescription = do-  path <- fixtureFilePath "profiles/decisions.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load decisions profile: " <> err)-    Right spec ->-      assertEqual-        (Just "The decision this one replaces, when it replaces one.")-        (profileFieldDescription spec "supersedes")---- | The JSON encoding is pinned field by field, so a future refactor cannot--- silently rename a key. The @type@ key matters most: the Haskell field is--- @type_@, and consumers must never see that.-testProfileJsonShape :: IO (Either Text ())-testProfileJsonShape = do-  path <- fixtureFilePath "profiles/decisions.dhall"-  result <- loadProfileFile path-  pure $ case result of-    Left err -> Left ("failed to load document ID profile: " <> err)-    Right spec ->-      assertEqual-        ( object-            [ "name" .= ("decisions" :: Text),-              "description" .= ("How this team records architectural decisions." :: Text),-              "guidance" .= (Nothing :: Maybe Text),-              "okfVersion" .= ("0.1" :: Text),-              -- Encoded even when absent, so a consumer reads one shape rather-              -- than having to distinguish a missing key from a null one.-              "requireBundleVersion" .= (Nothing :: Maybe Text),-              "allowUnknownTypes" .= False,-              "allowUnknownFields" .= True,-              "idField" .= ("docId" :: Text),-              "frontmatter"-                .= object-                  [ "required"-                      .= [ object-                             [ "field" .= ("type" :: Text),-                               "description"-                                 .= ("The OKF concept type; must be a type rule below." :: Text),-                               "allowedValues" .= ([] :: [Text]),-                               "cardinality" .= ("any" :: Text),-                               "format" .= (Nothing :: Maybe Text),-                               "elementFields" .= (Nothing :: Maybe Value),-                               "objectFields" .= (Nothing :: Maybe Value),-                               "reference" .= (Nothing :: Maybe HandleReferenceRule),-                               "path" .= (Nothing :: Maybe PathReferenceRule),-                               "when" .= (Nothing :: Maybe FieldCondition),-                               "uniqueBy" .= (Nothing :: Maybe Text)-                             ],-                           object-                             [ "field" .= ("title" :: Text),-                               "description" .= (Nothing :: Maybe Text),-                               "allowedValues" .= ([] :: [Text]),-                               "cardinality" .= ("any" :: Text),-                               "format" .= (Nothing :: Maybe Text),-                               "elementFields" .= (Nothing :: Maybe Value),-                               "objectFields" .= (Nothing :: Maybe Value),-                               "reference" .= (Nothing :: Maybe HandleReferenceRule),-                               "path" .= (Nothing :: Maybe PathReferenceRule),-                               "when" .= (Nothing :: Maybe FieldCondition),-                               "uniqueBy" .= (Nothing :: Maybe Text)-                             ]-                         ],-                    "recommended"-                      .= [ object-                             [ "field" .= ("status" :: Text),-                               "description"-                                 .= ("One of: proposed, accepted, superseded." :: Text),-                               "allowedValues" .= ([] :: [Text]),-                               "cardinality" .= ("any" :: Text),-                               "format" .= (Nothing :: Maybe Text),-                               "elementFields" .= (Nothing :: Maybe Value),-                               "objectFields" .= (Nothing :: Maybe Value),-                               "reference" .= (Nothing :: Maybe HandleReferenceRule),-                               "path" .= (Nothing :: Maybe PathReferenceRule),-                               "when" .= (Nothing :: Maybe FieldCondition),-                               "uniqueBy" .= (Nothing :: Maybe Text)-                             ]-                         ],-                    "optional"-                      .= [ object-                             [ "field" .= ("supersedes" :: Text),-                               "description"-                                 .= ("The decision this one replaces, when it replaces one." :: Text),-                               "allowedValues" .= ([] :: [Text]),-                               "cardinality" .= ("any" :: Text),-                               "format" .= (Nothing :: Maybe Text),-                               "elementFields" .= (Nothing :: Maybe Value),-                               "objectFields" .= (Nothing :: Maybe Value),-                               "reference" .= (Nothing :: Maybe HandleReferenceRule),-                               "path" .= (Nothing :: Maybe PathReferenceRule),-                               "when" .= (Nothing :: Maybe FieldCondition),-                               "uniqueBy" .= (Nothing :: Maybe Text)-                             ]-                         ]-                  ],-              "types"-                .= [ object-                       [ "type" .= ("Decision Record" :: Text),-                         "description"-                           .= ("One accepted decision, never edited after acceptance." :: Text),-                         "guidance" .= (Nothing :: Maybe Text),-                         "frontmatter"-                           .= object-                             [ "required" .= ([] :: [FieldRule]),-                               "recommended" .= ([] :: [FieldRule]),-                               "optional" .= ([] :: [FieldRule])-                             ],-                         "pathPattern" .= ("decisions/*" :: Text),-                         "resourceScheme" .= (Nothing :: Maybe Text),-                         "requireSchemaSection" .= False,-                         "schemaColumns" .= ([] :: [Text]),-                         "idPrefix" .= ("ADR" :: Text)-                       ]-                   ]-            ]-        )-        (toJSON spec)--testFieldFormatJsonShape :: Either Text ()-testFieldFormatJsonShape =-  assertEqual-    [ String "rfc3339-utc",-      String "date",-      String "uri",-      object ["uriWithScheme" .= ("mori" :: Text)],-      object ["documentHandle" .= ("ADR" :: Text)]-    ]-    (map toJSON [Rfc3339Utc, Date, Uri, UriWithScheme "mori", DocumentHandle "ADR"])--testFieldConditionJsonShape :: Either Text ()-testFieldConditionJsonShape =-  assertEqual-    (object ["field" .= ("status" :: Text), "hasValue" .= (["superseded"] :: [Text])])-    (toJSON (FieldCondition "status" ["superseded"]))--testHandleReferenceJsonShape :: Either Text ()-testHandleReferenceJsonShape =-  assertEqual-    ( object-        [ "localPrefix" .= ("ADR" :: Text),-          "externalUriSchemes" .= (["mori", "https"] :: [Text]),-          "allowSelf" .= False,-          "allowLocal" .= True,-          "externalUriPattern" .= (Nothing :: Maybe Text)-        ]-    )-    (toJSON (handleReferenceRule "ADR" ["mori", "https"] False))---- | A registry record enumerates every field that decodes as a profile, one--- level down as well as at the top, sorted by export path. The @Profile@ schema--- record and the @note@ string contribute nothing.-testRegistryEnumeratesProfiles :: IO (Either Text ())-testRegistryEnumeratesProfiles = do-  path <- fixtureFilePath "registry/package.dhall"-  loaded <- loadRegistry (RegistryFile path)-  pure $ case loaded of-    Left err -> Left ("failed to load fixture registry: " <> err)-    Right entries -> do-      -- `legacy` is a frozen okf 0.2.x descriptor: it enumerates only because-      -- the registry walk falls back to the legacy decoder.-      assertEqual ["legacy", "nested.decisions", "postgresql"] (map (^. #export) entries)-      case findRegistryEntry "legacy" entries of-        Nothing -> Left "expected an entry at export path legacy"-        Just entry -> do-          assertEqual "legacy" (entry ^. #spec . #name)-          assertEqual Nothing (entry ^. #spec . #description)-      case findRegistryEntry "postgresql" entries of-        Nothing -> Left "expected an entry at export path postgresql"-        Just entry -> assertEqual "shinzui-postgresql" (entry ^. #spec . #name)-      assertEqual Nothing (findRegistryEntry "nope" entries)-      assertBool-        "expected findRegistryEntry to resolve the nested export"-        (isJust (findRegistryEntry "nested.decisions" entries))---- | The built-in registry pin and this offline snapshot move together. Loading--- the snapshot catches a catalogue descriptor that the current decoder cannot--- read without making the test suite depend on GitHub or Dhall's cache.-testPinnedCatalogueDecodes :: IO (Either Text ())-testPinnedCatalogueDecodes = do-  path <- fixtureFilePath "catalogue/package.dhall"-  loaded <- loadRegistry (RegistryFile path)-  pure $ case loaded of-    Left err -> Left ("failed to load pinned catalogue snapshot: " <> err)-    Right entries -> do-      assertEqual-        [ "assurance.failureModes",-          "assurance.reviews",-          "coordination.bugReports",-          "coordination.capabilities",-          "coordination.improvementRequests",-          "coordination.useCases",-          "documentation.architectureDecisions",-          "documentation.patternCatalog",-          "documentation.researchDocuments",-          "documentation.userDocumentation",-          "okfV02",-          "postgresql",-          "tanPostgresql"-        ]-        (List.sort (map (^. #export) entries))-      assertBool-        "expected every pinned catalogue profile to have a non-empty name"-        (all (not . Text.null . (^. #spec . #name)) entries)-      assertBool-        "expected every pinned catalogue profile to have a non-empty okfVersion"-        (all (not . Text.null . (^. #spec . #okfVersion)) entries)---- | A registry reference that is itself a profile yields one entry whose export--- path is empty.-testRegistryRootProfile :: IO (Either Text ())-testRegistryRootProfile = do-  path <- fixtureFilePath "profiles/decisions.dhall"-  loaded <- loadRegistry (RegistryFile path)-  pure $ case loaded of-    Left err -> Left ("failed to load root profile registry: " <> err)-    Right entries -> do-      assertEqual [""] (map (^. #export) entries)-      assertEqual ["decisions"] (map (^. #spec . #name) entries)---- | A directory holding @package.dhall@ resolves to that file; anything else--- is handed to Dhall verbatim.-testResolveRegistryRef :: IO (Either Text ())-testResolveRegistryRef = do-  directory <- fixturePath "registry"-  resolvedDirectory <- resolveRegistryRef (Text.pack directory)-  filePath <- fixtureFilePath "profiles/decisions.dhall"-  resolvedFile <- resolveRegistryRef (Text.pack filePath)-  resolvedExpression <- resolveRegistryRef "./nowhere/at/all.dhall"-  pure $ do-    assertEqual (RegistryFile (directory </> "package.dhall")) resolvedDirectory-    assertEqual (RegistryFile filePath) resolvedFile-    assertEqual (RegistryExpression "./nowhere/at/all.dhall") resolvedExpression---- | A reference that cannot be evaluated reports an error rather than throwing.-testRegistryLoadFailure :: IO (Either Text ())-testRegistryLoadFailure = do-  loaded <- loadRegistry (RegistryFile "/nonexistent/registry.dhall")-  pure $ case loaded of-    Right entries -> Left ("expected a load failure, got " <> Text.pack (show (length entries)) <> " entries")-    Left message -> assertBool "expected a non-empty error message" (not (Text.null message))--testLooksLikeRegistryPath :: Either Text ()-testLooksLikeRegistryPath = do-  assertEqual-    [True, True, True, True, True, True, False, False, False]-    ( map-        looksLikeRegistryPath-        [ "./profiles/package.dhall",-          "../profiles/package.dhall",-          "/profiles/package.dhall",-          "~/profiles/package.dhall",-          "profiles/package.dhall",-          "profile.dhall",-          "https://example.test/package.dhall sha256:abc",-          "http://example.test/package.dhall",-          "{ profile = 1 }"-        ]-    )--testRegistryDetailedFailures :: IO (Either Text ())-testRegistryDetailedFailures =-  withDiscoveryTree "okf-registry-errors" [] $ \root -> do-    profilePath <- fixtureFilePath "profiles/decisions.dhall"-    absoluteProfilePath <- makeAbsolute profilePath-    directoryResult <- loadRegistryDetailed (RegistryExpression (Text.pack root))-    missingResult <- loadRegistryDetailed (RegistryExpression (Text.pack (root </> "missing" </> "package.dhall")))-    invalidResult <- loadRegistryDetailed (RegistryExpression "{ profile =")-    hashResult <--      loadRegistryDetailed-        ( RegistryExpression-            ( Text.pack absoluteProfilePath-                <> " sha256:0000000000000000000000000000000000000000000000000000000000000000"-            )-        )-    pure $ do-      assertEqual (Left (RegistryDirectoryMissingPackage root)) directoryResult-      assertEqual (Left (RegistryPathNotFound (root </> "missing" </> "package.dhall"))) missingResult-      assertEqual (Left RegistryInvalidDhall) invalidResult-      assertEqual (Left RegistryHashMismatch) hashResult-      assertBool-        "typed summaries must not contain ANSI escape bytes"-        ( all-            (not . Text.isInfixOf "\ESC[")-            [ renderRegistryLoadErrorMessage (RegistryDirectoryMissingPackage root),-              renderRegistryLoadErrorMessage RegistryHashMismatch,-              renderRegistryLoadErrorMessage RegistryInvalidDhall-            ]-        )--testDiscoverProfileDescriptors :: IO (Either Text ())-testDiscoverProfileDescriptors = do-  root <- fixturePath "profile-discovery"-  found <--    ProfileDiscovery.discoverProfileDescriptors-      ProfileDiscovery.defaultProfileDiscoveryOptions-      root-  pure $-    assertEqual-      [ normalise (root </> "nested" </> "valid-nested.dhall"),-        normalise (root </> "valid.dhall")-      ]-      found--testProfileDescriptorQualification :: IO (Either Text ())-testProfileDescriptorQualification = do-  valid <- fixtureFilePath "profile-discovery/valid.dhall"-  registry <- fixtureFilePath "profile-discovery/registry.dhall"-  notProfile <- fixtureFilePath "profile-discovery/not-a-profile.dhall"-  invalid <- fixtureFilePath "profile-discovery/invalid.dhall"-  ignoredFile <- fixtureFilePath "profile-discovery/ignored.txt"-  results <--    traverse-      ProfileDiscovery.fileQualifiesAsProfileDescriptor-      [valid, registry, notProfile, invalid, ignoredFile]-  pure (assertEqual [True, False, False, False, False] results)--testProfileDiscoveryMissingRoot :: IO (Either Text ())-testProfileDiscoveryMissingRoot = do-  found <--    ProfileDiscovery.discoverProfileDescriptors-      ProfileDiscovery.defaultProfileDiscoveryOptions-      "/nonexistent/okf-profile-discovery-root"-  pure (assertEqual [] found)--testProfileDiscoverySkipsSymlink :: IO (Either Text ())-testProfileDiscoverySkipsSymlink =-  withDiscoveryTree "okf-profile-discovery-symlink" [] $ \root -> do-    target <- fixtureFilePath "profile-discovery/valid.dhall" >>= makeAbsolute-    createFileLink target (root </> "linked.dhall")-    found <--      ProfileDiscovery.discoverProfileDescriptors-        ProfileDiscovery.defaultProfileDiscoveryOptions-        root-    pure (assertEqual [] found)--testProfileDiscoveryHonoursMaxDepth :: IO (Either Text ())-testProfileDiscoveryHonoursMaxDepth = do-  root <- fixturePath "profile-discovery"-  shallow <--    ProfileDiscovery.discoverProfileDescriptors-      ProfileDiscovery.defaultProfileDiscoveryOptions-      root-  deeper <--    ProfileDiscovery.discoverProfileDescriptors-      ProfileDiscovery.defaultProfileDiscoveryOptions {ProfileDiscovery.maxDepth = 6}-      root-  let deepest = normalise (root </> "deep" </> "a" </> "b" </> "c" </> "d" </> "e" </> "valid-too-deep.dhall")-  pure $ do-    assertBool "default depth should exclude the deep descriptor" (deepest `notElem` shallow)-    assertBool "expanded depth should include the deep descriptor" (deepest `elem` deeper)--testProfileDiscoveryRejectsRemote :: IO (Either Text ())-testProfileDiscoveryRejectsRemote = do-  textRemote <- fixtureFilePath "profile-discovery/remote.dhall"-  bytesRemote <- fixtureFilePath "profile-discovery/remote-bytes.dhall"-  loaded <- traverse ProfileDiscovery.loadProfileDescriptorWithoutNetwork [textRemote, bytesRemote]-  qualifies <- traverse ProfileDiscovery.fileQualifiesAsProfileDescriptor [textRemote, bytesRemote]-  pure $ do-    for_ loaded $ \case-      Right profile -> Left ("expected remote descriptor rejection, decoded " <> profile ^. #name)-      Left message ->-        assertBool-          "expected the dedicated no-network callback to reject the import"-          ("Remote imports are disabled during profile discovery" `Text.isInfixOf` message)-    assertEqual [False, False] qualifies--testProfileSourceLabels :: Either Text ()-testProfileSourceLabels = do-  assertEqual-    "okf-profiles"-    ( renderProfileSourceLabel-        (RegistrySource defaultRegistryReference (RegistryExpression defaultRegistryReference))-    )-  assertEqual-    "okf-v0-2"-    ( renderProfileSourceLabel-        (RegistrySource "docs/profiles/okf-v0-2.dhall" (RegistryFile "docs/profiles/okf-v0-2.dhall"))-    )-  assertEqual "local" (renderProfileSourceLabel (DescriptorSource "docs/profiles/okf-v0-2.dhall"))-  assertEqual-    (Text.pack (normalise "docs/profiles/../profiles/okf-v0-2.dhall"))-    (renderProfileSourceReference (DescriptorSource "docs/profiles/../profiles/okf-v0-2.dhall"))---- | Loading one source wraps every otherwise unchanged registry entry with its--- provenance.-testProfileSourceWrapper :: IO (Either Text ())-testProfileSourceWrapper = do-  path <- fixtureFilePath "profiles/decisions.dhall"-  let profileSource = RegistrySource (Text.pack path) (RegistryFile path)-  loaded <- loadProfileSource profileSource-  pure $ case loaded of-    Left err -> Left ("failed to load sourced profile fixture: " <> err)-    Right profiles -> do-      assertEqual [profileSource] (map (^. #source) profiles)-      assertEqual [""] (map (^. #entry . #export) profiles)--testDescriptorSourceWrapper :: IO (Either Text ())-testDescriptorSourceWrapper = do-  path <- fixtureFilePath "profile-discovery/valid.dhall"-  let profileSource = DescriptorSource (normalise path)-  loaded <- loadProfileSource (DescriptorSource (takeDirectory path </> "." </> "valid.dhall"))-  pure $ case loaded of-    Left err -> Left ("failed to load descriptor source fixture: " <> err)-    Right profiles -> do-      assertEqual [profileSource] (map (^. #source) profiles)-      assertEqual ["valid"] (map (^. #entry . #export) profiles)--testDescriptorSourceFailure :: IO (Either Text ())-testDescriptorSourceFailure = do-  path <- fixtureFilePath "profile-discovery/not-a-profile.dhall"-  let profileSource = DescriptorSource path-  (failures, profiles) <- loadProfileSources [profileSource]-  pure $ do-    assertEqual [] profiles-    assertEqual [DescriptorSource (normalise path)] (map (^. #failedSource) failures)-    assertBool-      "expected the descriptor decode failure to carry a reason"-      (all (not . Text.null . (^. #failureReason)) failures)---- | Multi-source enumeration preserves source order and each registry's--- export ordering rather than globally interleaving equal-looking paths.-testProfileSourcesMergeInOrder :: IO (Either Text ())-testProfileSourcesMergeInOrder = do-  (publicSource, houseSource) <- fixtureProfileSources-  (failures, profiles) <- loadProfileSources [publicSource, houseSource]-  pure $ do-    assertEqual [] failures-    assertEqual-      [ "legacy",-        "nested.decisions",-        "postgresql",-        "postgresql",-        "runbooks"-      ]-      (map (^. #entry . #export) profiles)-    assertEqual-      (replicate 3 publicSource <> replicate 2 houseSource)-      (map (^. #source) profiles)--testMixedProfileSourcesMergeInOrder :: IO (Either Text ())-testMixedProfileSourcesMergeInOrder = do-  (publicSource, _houseSource) <- fixtureProfileSources-  descriptorPath <- fixtureFilePath "profile-discovery/valid.dhall"-  let descriptorSource = DescriptorSource (normalise descriptorPath)-  (failures, profiles) <- loadProfileSources [publicSource, descriptorSource]-  pure $ do-    assertEqual [] failures-    assertEqual-      ["legacy", "nested.decisions", "postgresql", "valid"]-      (map (^. #entry . #export) profiles)-    assertEqual-      (replicate 3 publicSource <> [descriptorSource])-      (map (^. #source) profiles)--testProfileSourcesPartialFailure :: IO (Either Text ())-testProfileSourcesPartialFailure = do-  (_publicSource, houseSource) <- fixtureProfileSources-  let missingSource = RegistrySource "/nonexistent/registry.dhall" (RegistryFile "/nonexistent/registry.dhall")-  (failures, profiles) <- loadProfileSources [missingSource, houseSource]-  pure $ do-    assertEqual [missingSource] (map (^. #failedSource) failures)-    assertBool-      "expected the captured source failure to include a reason"-      (all (not . Text.null . (^. #failureReason)) failures)-    assertEqual ["postgresql", "runbooks"] (map (^. #entry . #export) profiles)--testProfileSourcesExposeCollisions :: IO (Either Text ())-testProfileSourcesExposeCollisions = do-  (publicSource, houseSource) <- fixtureProfileSources-  (_failures, profiles) <- loadProfileSources [publicSource, houseSource]-  pure $-    assertEqual-      [publicSource, houseSource]-      (map (^. #source) (findSourcedProfiles "postgresql" profiles))--testProfileSourcesDropDuplicates :: IO (Either Text ())-testProfileSourcesDropDuplicates = do-  (_publicSource, houseSource) <- fixtureProfileSources-  (failures, profiles) <- loadProfileSources [houseSource, houseSource]-  pure $ do-    assertEqual [] failures-    assertEqual [houseSource] (normalizeProfileSources [houseSource, houseSource])-    assertEqual ["postgresql", "runbooks"] (map (^. #entry . #export) profiles)--fixtureProfileSources :: IO (ProfileSource, ProfileSource)-fixtureProfileSources = do-  publicPath <- fixtureFilePath "registry/package.dhall"-  housePath <- fixtureFilePath "registry-house/package.dhall"-  pure-    ( RegistrySource (Text.pack publicPath) (RegistryFile publicPath),-      RegistrySource (Text.pack housePath) (RegistryFile housePath)-    )--testParseDocumentId :: Either Text ()-testParseDocumentId = do-  assertEqual-    (Just (DocumentId {prefix = "ADR", number = 7}))-    (parseDocumentId "ADR-7")-  mapM_-    (\invalid -> assertEqual Nothing (parseDocumentId invalid))-    ["ADR-007", "ADR-0", "ADR-", "-7", "ADR 7", "ADR-7-extra"]-  assertEqual (Just "ADR-7") (renderDocumentId <$> parseDocumentId "ADR-7")--testDocumentIdsInBundle :: IO (Either Text ())-testDocumentIdsInBundle = do-  descriptorPath <- fixtureFilePath "profiles/decisions.dhall"-  loaded <- loadProfileFile descriptorPath-  root <- fixturePath "doc-ids"-  concepts <- readBundle root-  pure $ case loaded of-    Left err -> Left ("failed to load document ID profile: " <> err)-    Right spec -> do-      useMarkdown <- parseTestConceptId "decisions/use-markdown"-      usePostgres <- parseTestConceptId "decisions/use-postgres"-      adoptOkf <- parseTestConceptId "decisions/adopt-okf"-      assertEqual-        [ (DocumentId "ADR" 1, useMarkdown),-          (DocumentId "ADR" 2, usePostgres),-          (DocumentId "ADR" 3, adoptOkf)-        ]-        (documentIdsInBundle spec concepts)--testNextDocumentId :: Either Text ()-testNextDocumentId = do-  firstConcept <--    profileConcept-      "decisions/first"-      [("type", String "Decision Record"), ("title", String "First"), ("docId", String "ADR-1")]-      "# First\n"-  thirdConcept <--    profileConcept-      "decisions/third"-      [("type", String "Decision Record"), ("title", String "Third"), ("docId", String "ADR-3")]-      "# Third\n"-  let concepts = [firstConcept, thirdConcept]-  assertEqual (DocumentId "ADR" 4) (nextDocumentId testDocumentIdProfileSpec concepts "ADR")-  assertEqual (DocumentId "RFC" 1) (nextDocumentId testDocumentIdProfileSpec concepts "RFC")--testFindConceptsByDocumentId :: IO (Either Text ())-testFindConceptsByDocumentId = do-  validRoot <- fixturePath "doc-ids"-  validConcepts <- readBundle validRoot-  deviationRoot <- fixturePath "doc-id-deviations"-  deviationConcepts <- readBundle deviationRoot-  pure $ do-    usePostgres <- parseTestConceptId "decisions/use-postgres"-    firstId <- parseTestConceptId "decisions/first"-    secondId <- parseTestConceptId "decisions/second"-    assertEqual-      [usePostgres]-      (conceptIdOf <$> findConceptsByDocumentId Nothing "ADR-2" validConcepts)-    assertEqual-      [firstId, secondId]-      (conceptIdOf <$> findConceptsByDocumentId (Just "docId") "ADR-1" deviationConcepts)---- | An undocumented frontmatter key: the validation tests care about names, not--- prose, and descriptions never affect validation.-requiredField :: Text -> FieldRule-requiredField key = FieldRule {field = key, description = Nothing, allowedValues = [], cardinality = Any, format = Nothing, elementFields = Nothing, objectFields = Nothing, reference = Nothing, path = Nothing, when = Nothing, uniqueBy = Nothing}---- | Build a 'FieldRule' positionally in the argument order this file used--- before 'FieldRule' gained @objectFields@, filling that member in as--- 'Nothing'. The dozens of call sites below constrain lists, formats,--- conditions, and references rather than object shapes, so spelling out a ninth--- 'Nothing' at each of them would add noise and no information. A test that--- does exercise object rules builds its rule with record syntax instead.-fieldRule ::-  Text ->-  Maybe Text ->-  [Text] ->-  Cardinality ->-  Maybe FieldFormat ->-  Maybe NestedRules ->-  Maybe HandleReferenceRule ->-  Maybe FieldCondition ->-  FieldRule-fieldRule key description allowedValues cardinality format elementFields reference condition =-  FieldRule-    { field = key,-      description,-      allowedValues,-      cardinality,-      format,-      elementFields,-      objectFields = Nothing,-      reference,-      path = Nothing,-      when = condition,-      uniqueBy = Nothing-    }--handleReferenceRule :: Text -> [Text] -> Bool -> HandleReferenceRule-handleReferenceRule prefix schemes selfAllowed =-  HandleReferenceRule-    { localPrefix = prefix,-      externalUriSchemes = schemes,-      allowSelf = selfAllowed,-      allowLocal = True,-      externalUriPattern = Nothing-    }--nestedFieldRule :: Text -> Maybe Text -> [Text] -> Cardinality -> Maybe FieldFormat -> Maybe PathReferenceRule -> Maybe FieldCondition -> NestedFieldRule-nestedFieldRule key description allowedValues cardinality format path condition =-  NestedFieldRule-    { field = key,-      description,-      allowedValues,-      cardinality,-      format,-      path,-      when = condition,-      reference = Nothing-    }---- | A standalone profile literal so the validation tests do not depend on the--- Dhall fixture. One rule: PostgreSQL Table, fully constrained.-testProfileSpec :: ProfileSpec-testProfileSpec =-  ProfileSpec-    { name = "test-postgresql",-      description = Nothing,-      guidance = Nothing,-      okfVersion = "0.1",-      frontmatter =-        FrontmatterRules-          { required = [requiredField "type", requiredField "title"],-            recommended = [],-            optional = []-          },-      allowUnknownTypes = False,-      allowUnknownFields = True,-      idField = Nothing,-      requireBundleVersion = Nothing,-      types =-        [ TypeRule-            { type_ = "PostgreSQL Table",-              description = Nothing,-              guidance = Nothing,-              frontmatter = emptyTestFrontmatterRules,-              pathPattern = Just "schemas/*/tables/*",-              resourceScheme = Just "postgresql",-              requireSchemaSection = True,-              schemaColumns = ["Column", "Type", "Nullable", "Description"],-              idPrefix = Nothing-            }-        ]-    }--testDocumentIdProfileSpec :: ProfileSpec-testDocumentIdProfileSpec =-  ProfileSpec-    { name = "test-decisions",-      description = Nothing,-      guidance = Nothing,-      okfVersion = "0.1",-      frontmatter =-        FrontmatterRules-          { required = [requiredField "type", requiredField "title"],-            recommended = [],-            optional = []-          },-      allowUnknownTypes = False,-      allowUnknownFields = True,-      idField = Just "docId",-      requireBundleVersion = Nothing,-      types =-        [ TypeRule-            { type_ = "Decision Record",-              description = Nothing,-              guidance = Nothing,-              frontmatter = emptyTestFrontmatterRules,-              pathPattern = Just "decisions/*",-              resourceScheme = Nothing,-              requireSchemaSection = False,-              schemaColumns = [],-              idPrefix = Just "ADR"-            }-        ]-    }--emptyTestFrontmatterRules :: FrontmatterRules-emptyTestFrontmatterRules = FrontmatterRules {required = [], recommended = [], optional = []}--typeAwareProfileSpec :: ProfileSpec-typeAwareProfileSpec =-  ProfileSpec-    { name = "type-aware",-      description = Nothing,-      guidance = Nothing,-      okfVersion = "0.1",-      frontmatter =-        FrontmatterRules-          { required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing, fieldRule "title" (Just "Global title.") [] Any Nothing Nothing Nothing Nothing],-            recommended = [fieldRule "owner" (Just "Profile-level owner.") [] Any Nothing Nothing Nothing Nothing],-            optional = []-          },-      allowUnknownTypes = True,-      allowUnknownFields = True,-      idField = Nothing,-      requireBundleVersion = Nothing,-      types =-        [ TypeRule-            { type_ = "Owned Concept",-              description = Nothing,-              guidance = Nothing,-              frontmatter =-                FrontmatterRules-                  { required = [fieldRule "owner" (Just "Responsible person.") [] Any Nothing Nothing Nothing Nothing],-                    recommended = [fieldRule "reviewer" (Just "Second pair of eyes.") [] Any Nothing Nothing Nothing Nothing, fieldRule "title" (Just "Type title.") [] Any Nothing Nothing Nothing Nothing],-                    optional = []-                  },-              pathPattern = Nothing,-              resourceScheme = Nothing,-              requireSchemaSection = False,-              schemaColumns = [],-              idPrefix = Nothing-            }-        ]-    }--testCompileProfileDefinitionErrors :: Either Text ()-testCompileProfileDefinitionErrors = do-  let duplicateField = fieldRule "title" Nothing [] Any Nothing Nothing Nothing Nothing-      invalid =-        typeAwareProfileSpec-          { frontmatter =-              FrontmatterRules-                { required = [duplicateField, duplicateField],-                  recommended = [duplicateField],-                  optional = []-                },-            types = (typeAwareProfileSpec ^. #types) <> (typeAwareProfileSpec ^. #types)-          }-  case compileProfile invalid of-    Right _ -> Left "expected invalid profile definition"-    Left errors ->-      assertEqual-        [ DuplicateFieldRule Nothing "required" "title",-          ConflictingFieldRequirement Nothing "title",-          DuplicateTypeRule "Owned Concept"-        ]-        (toList errors)--testCompiledProfileMerge :: Either Text ()-testCompiledProfileMerge = do-  compiled <- firstShow (compileProfile typeAwareProfileSpec)-  assertEqual (Just "Type title.") (profileFieldDescriptionForType compiled "Owned Concept" "title")-  assertEqual (Just "Responsible person.") (profileFieldDescriptionForType compiled "Owned Concept" "owner")-  assertEqual (Just "Global title.") (profileFieldDescriptionForType compiled "Unknown Concept" "title")-  concept <- profileConcept "owned/one" [("type", String "Owned Concept")] "# One\n"-  cid <- parseTestConceptId "owned/one"-  assertEqual-    [MissingProfileField cid "owner" Nothing, MissingProfileField cid "title" Nothing]-    (validateProfile PermissiveConformance compiled [concept])--vocabularyProfileSpec :: ProfileSpec-vocabularyProfileSpec =-  typeAwareProfileSpec-    { frontmatter =-        FrontmatterRules-          { required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing],-            recommended = [fieldRule "status" Nothing ["draft", "approved", "approved"] Any Nothing Nothing Nothing Nothing],-            optional = []-          },-      types =-        [ withTypeFrontmatter-            FrontmatterRules-              { required = [fieldRule "status" Nothing ["approved", "archived"] Any Nothing Nothing Nothing Nothing],-                recommended = [],-                optional = []-              }-            (firstTypeRule typeAwareProfileSpec)-        ]-    }--fieldPath :: Text -> FieldPath-fieldPath key = FieldPath (FieldName key :| [])--testCompiledVocabularyIntersection :: Either Text ()-testCompiledVocabularyIntersection = do-  compiled <- firstShow (compileProfile vocabularyProfileSpec)-  concept <- profileConcept "owned/one" [("type", String "Owned Concept"), ("status", String "draft")] "# One\n"-  cid <- parseTestConceptId "owned/one"-  assertEqual-    [ValueNotInVocabulary cid (fieldPath "status") ["approved"] (String "draft")]-    (validateProfile PermissiveConformance compiled [concept])--testUnsatisfiableVocabulary :: Either Text ()-testUnsatisfiableVocabulary = do-  let disjoint =-        vocabularyProfileSpec-          { types =-              [ withTypeFrontmatter-                  FrontmatterRules-                    { required = [fieldRule "status" Nothing ["closed"] Any Nothing Nothing Nothing Nothing],-                      recommended = [],-                      optional = []-                    }-                  (firstTypeRule vocabularyProfileSpec)-              ]-          }-  assertEqual-    (Left (UnsatisfiableVocabulary (Just "Owned Concept") "status" ["draft", "approved"] ["closed"] :| []))-    (compileProfile disjoint)--testCompiledCardinality :: Either Text ()-testCompiledCardinality = do-  let profileRules =-        FrontmatterRules-          { required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing],-            recommended = [fieldRule "status" Nothing [] Scalar Nothing Nothing Nothing Nothing],-            optional = []-          }-      typeRules cardinality =-        FrontmatterRules-          { required = [fieldRule "status" Nothing [] cardinality Nothing Nothing Nothing Nothing],-            recommended = [],-            optional = []-          }-      baseType = firstTypeRule typeAwareProfileSpec-      compatible =-        typeAwareProfileSpec-          { frontmatter = profileRules,-            types = [withTypeFrontmatter (typeRules Any) baseType]-          }-      contradictory = compatible {types = [withTypeFrontmatter (typeRules List) baseType]}-  compiled <- firstShow (compileProfile compatible)-  valid <- profileConcept "owned/cardinality" [("type", String "Owned Concept"), ("status", Number 3)] "# Valid\n"-  invalid <- profileConcept "owned/cardinality" [("type", String "Owned Concept"), ("status", toJSON (["draft"] :: [Text]))] "# Invalid\n"-  cid <- parseTestConceptId "owned/cardinality"-  assertEqual [] (validateProfile PermissiveConformance compiled [valid])-  assertEqual-    [CardinalityMismatch cid (fieldPath "status") Scalar (toJSON (["draft"] :: [Text]))]-    (validateProfile PermissiveConformance compiled [invalid])-  assertEqual-    (Left (ConflictingCardinality (Just "Owned Concept") "status" Scalar List :| []))-    (compileProfile contradictory)--testVocabularyValidation :: Either Text ()-testVocabularyValidation = do-  let openVocabulary =-        vocabularyProfileSpec-          { frontmatter =-              FrontmatterRules-                { required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing],-                  recommended = [fieldRule "status" Nothing ["draft", "approved"] Any Nothing Nothing Nothing Nothing],-                  optional = []-                },-            types = []-          }-  compiled <- firstShow (compileProfile openVocabulary)-  validString <- profileConcept "valid-string" [("type", String "Extension"), ("status", String "draft")] "# Valid\n"-  validList <- profileConcept "valid-list" [("type", String "Extension"), ("status", toJSON (["draft", "approved"] :: [Text]))] "# Valid\n"-  absent <- profileConcept "absent" [("type", String "Extension")] "# Absent\n"-  invalidString <- profileConcept "invalid-string" [("type", String "Extension"), ("status", String "banana")] "# Invalid\n"-  invalidList <- profileConcept "invalid-list" [("type", String "Extension"), ("status", toJSON (["draft", "banana"] :: [Text]))] "# Invalid\n"-  invalidShape <- profileConcept "invalid-shape" [("type", String "Extension"), ("status", toJSON (1 :: Int))] "# Invalid\n"-  invalidStringId <- parseTestConceptId "invalid-string"-  invalidListId <- parseTestConceptId "invalid-list"-  invalidShapeId <- parseTestConceptId "invalid-shape"-  assertEqual [] (validateProfile PermissiveConformance compiled [validString, validList, absent])-  assertEqual-    [ValueNotInVocabulary invalidStringId (fieldPath "status") ["draft", "approved"] (String "banana")]-    (validateProfile PermissiveConformance compiled [invalidString])-  assertEqual-    [ValueNotInVocabulary invalidListId (fieldPath "status") ["draft", "approved"] (toJSON (["draft", "banana"] :: [Text]))]-    (validateProfile PermissiveConformance compiled [invalidList])-  assertEqual-    [ValueNotInVocabulary invalidShapeId (fieldPath "status") ["draft", "approved"] (toJSON (1 :: Int))]-    (validateProfile PermissiveConformance compiled [invalidShape])--testCardinalityValidation :: Either Text ()-testCardinalityValidation = do-  cid <- parseTestConceptId "cardinality"-  let check cardinality actual = do-        compiled <- firstShow (compileProfile (singleCardinalityProfile True cardinality []))-        concept <- profileConcept "cardinality" [("type", String "Extension"), ("value", actual)] "# Cardinality\n"-        pure (validateProfile PermissiveConformance compiled [concept])-      mismatch cardinality actual = [CardinalityMismatch cid (fieldPath "value") cardinality actual]-      objectValue = object ["nested" .= (True :: Bool)]-      textList = toJSON (["one"] :: [Text])-      emptyList = toJSON ([] :: [Text])-  for_ [String "one", Number 0, Bool False] $ \actual ->-    check Scalar actual >>= assertEqual []-  for_ [textList, objectValue, Null] $ \actual ->-    check Scalar actual >>= assertEqual (mismatch Scalar actual)-  check List textList >>= assertEqual []-  for_ [String "one", Number 0, Bool False, objectValue, Null] $ \actual ->-    check List actual >>= assertEqual (mismatch List actual)-  check Any (String "one") >>= assertEqual []-  check Any textList >>= assertEqual []-  check Any (Bool False) >>= assertEqual [MissingProfileField cid "value" Nothing]-  check Scalar (String "   ") >>= assertEqual [MissingProfileField cid "value" Nothing]-  check List emptyList >>= assertEqual [MissingProfileField cid "value" Nothing]-  optionalCompiled <- firstShow (compileProfile (singleCardinalityProfile False Scalar []))-  optionalConcept <- profileConcept "cardinality" [("type", String "Extension"), ("value", textList)] "# Optional\n"-  assertEqual-    (mismatch Scalar textList)-    (validateProfile PermissiveConformance optionalCompiled [optionalConcept])--testCardinalityVocabularyInteraction :: Either Text ()-testCardinalityVocabularyInteraction = do-  cid <- parseTestConceptId "cardinality"-  scalarCompiled <- firstShow (compileProfile (singleCardinalityProfile True Scalar ["draft"]))-  let objectValue = object ["status" .= ("draft" :: Text)]-  objectConcept <- profileConcept "cardinality" [("type", String "Extension"), ("value", objectValue)] "# Object\n"-  assertEqual-    [CardinalityMismatch cid (fieldPath "value") Scalar objectValue]-    (validateProfile PermissiveConformance scalarCompiled [objectConcept])-  listCompiled <- firstShow (compileProfile (singleCardinalityProfile True List ["draft"]))-  let mixedList = toJSON ([String "draft", Number 1] :: [Value])-  listConcept <- profileConcept "cardinality" [("type", String "Extension"), ("value", mixedList)] "# List\n"-  assertEqual-    [ValueNotInVocabulary cid (fieldPath "value") ["draft"] mixedList]-    (validateProfile PermissiveConformance listCompiled [listConcept])--testCompiledFieldFormats :: Either Text ()-testCompiledFieldFormats = do-  let baseType = firstTypeRule typeAwareProfileSpec-      profileWith profileFormat typeFormat =-        typeAwareProfileSpec-          { frontmatter =-              FrontmatterRules-                { required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing, fieldRule "homepage" Nothing [] Any (Just profileFormat) Nothing Nothing Nothing],-                  recommended = [],-                  optional = []-                },-            types =-              [ withTypeFrontmatter-                  FrontmatterRules-                    { required = [fieldRule "homepage" Nothing [] Any (Just typeFormat) Nothing Nothing Nothing],-                      recommended = [],-                      optional = []-                    }-                  baseType-              ]-          }-  refined <- firstShow (compileProfile (profileWith Uri (UriWithScheme "https")))-  valid <- profileConcept "format-refinement" [("type", String "Owned Concept"), ("homepage", String "HTTPS://example.test/path")] "# Valid\n"-  invalid <- profileConcept "format-refinement" [("type", String "Owned Concept"), ("homepage", String "http://example.test/path")] "# Invalid\n"-  cid <- parseTestConceptId "format-refinement"-  assertEqual [] (validateProfile PermissiveConformance refined [valid])-  assertEqual-    [ValueFormatMismatch cid (fieldPath "homepage") (UriWithScheme "https") (String "http://example.test/path")]-    (validateProfile PermissiveConformance refined [invalid])-  assertEqual-    (Left (ConflictingFieldFormat (fieldPath "homepage") Date Rfc3339Utc :| []))-    (compileProfile (profileWith Date Rfc3339Utc))--testInvalidFormatParameters :: Either Text ()-testInvalidFormatParameters = do-  let invalid =-        typeAwareProfileSpec-          { frontmatter =-              FrontmatterRules-                { required =-                    [ fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing,-                      fieldRule "handle" Nothing [] Any (Just (DocumentHandle "1ADR")) Nothing Nothing Nothing,-                      fieldRule "source" Nothing [] Any (Just (UriWithScheme "https_")) Nothing Nothing Nothing-                    ],-                  recommended = [],-                  optional = []-                },-            types = []-          }-  assertEqual-    ( Left-        ( InvalidFormatParameter (fieldPath "handle") (DocumentHandle "1ADR") "1ADR"-            :| [InvalidFormatParameter (fieldPath "source") (UriWithScheme "https_") "https_"]-        )-    )-    (compileProfile invalid)--testNamedFormatValidation :: Either Text ()-testNamedFormatValidation = do-  cid <- parseTestConceptId "format"-  let check fieldFormat cardinality actual = do-        compiled <- firstShow (compileProfile (singleFormatProfile cardinality fieldFormat))-        concept <--          profileConcept-            "format"-            ([("type", String "Extension")] <> maybe [] (\value -> [("value", value)]) actual)-            "# Format\n"-        pure (validateProfile PermissiveConformance compiled [concept])-      mismatch fieldFormat actual = [ValueFormatMismatch cid (fieldPath "value") fieldFormat actual]-  for_ ["2024-02-29T23:59:59Z", "2026-07-29T17:00:00.125Z"] $ \value ->-    check Rfc3339Utc Any (Just (String value)) >>= assertEqual []-  for_ ["2026-13-45T99:99:99Z", "2026-07-29T17:00:00+01:00", "2026-07-29 17:00:00Z"] $ \value ->-    check Rfc3339Utc Any (Just (String value)) >>= assertEqual (mismatch Rfc3339Utc (String value))-  check Date Any (Just (String "2024-02-29")) >>= assertEqual []-  for_ ["2023-02-29", "2026-13-01", "2026-07-29T00:00:00Z"] $ \value ->-    check Date Any (Just (String value)) >>= assertEqual (mismatch Date (String value))-  for_ ["https://example.test/path", "urn:example:item"] $ \value ->-    check Uri Any (Just (String value)) >>= assertEqual []-  for_ ["relative/path", "https://example.test/bad%ZZ"] $ \value ->-    check Uri Any (Just (String value)) >>= assertEqual (mismatch Uri (String value))-  check (UriWithScheme "mori") Any (Just (String "MORI://haskell/time")) >>= assertEqual []-  check (UriWithScheme "mori") Any (Just (String "https://example.test"))-    >>= assertEqual (mismatch (UriWithScheme "mori") (String "https://example.test"))-  check (DocumentHandle "ADR") Any (Just (String "ADR-7")) >>= assertEqual []-  for_ ["ADR-007", "IR-7"] $ \value ->-    check (DocumentHandle "ADR") Any (Just (String value))-      >>= assertEqual (mismatch (DocumentHandle "ADR") (String value))-  let validUris = toJSON (["https://example.test", "urn:example:item"] :: [Text])-      mixedUris = toJSON ([String "https://example.test", Number 1] :: [Value])-  check Uri List (Just validUris) >>= assertEqual []-  check Uri List (Just mixedUris) >>= assertEqual (mismatch Uri mixedUris)-  check Uri Scalar (Just validUris)-    >>= assertEqual [CardinalityMismatch cid (fieldPath "value") Scalar validUris]-  check Uri Any (Just (Number 1)) >>= assertEqual (mismatch Uri (Number 1))-  check Uri Any Nothing >>= assertEqual []---- | The OKF v0.2 actor formats. Specification §7 defines exactly three shapes--- and 'parseActor' classifies them, so @actor@ accepts those three and reports--- everything else — including the specification's own illustrative--- @author: team:ga4-docs@ from §5.1, which §7's convention does not define. The--- case-sensitivity and empty-component cases come from 'Okf.Actor'.-testActorFormatValidation :: Either Text ()-testActorFormatValidation = do-  cid <- parseTestConceptId "format"-  let check fieldFormat value = do-        compiled <- firstShow (compileProfile (singleFormatProfile Any fieldFormat))-        concept <--          profileConcept "format" [("type", String "Extension"), ("value", String value)] "# Format\n"-        pure (validateProfile PermissiveConformance compiled [concept])-      mismatch fieldFormat value = [ValueFormatMismatch cid (fieldPath "value") fieldFormat (String value)]-  for_ ["human:ahormati", "process:finance-nightly", "reference_agent/gemini-2.5-pro"] $ \value ->-    check Actor value >>= assertEqual []-  for_ ["nadeem", "team:ga4-docs", "Human:ahormati", "human:", "/version", "producer/"] $ \value ->-    check Actor value >>= assertEqual (mismatch Actor value)-  check Profile.HumanActor "human:ahormati" >>= assertEqual []-  for_ ["process:finance-nightly", "reference_agent/gemini-2.5-pro", "nadeem"] $ \value ->-    check Profile.HumanActor value >>= assertEqual (mismatch Profile.HumanActor value)---- | The non-textual formats. A numeric /string/ is reported rather than--- coerced, which is the point of being able to declare the format at all.-testNonTextualFormatValidation :: Either Text ()-testNonTextualFormatValidation = do-  cid <- parseTestConceptId "format"-  let checkWith cardinality fieldFormat actual = do-        compiled <- firstShow (compileProfile (singleFormatProfile cardinality fieldFormat))-        concept <--          profileConcept "format" [("type", String "Extension"), ("value", actual)] "# Format\n"-        pure (validateProfile PermissiveConformance compiled [concept])-      check = checkWith Any-      mismatch fieldFormat actual = [ValueFormatMismatch cid (fieldPath "value") fieldFormat actual]-  for_ [Number 5000, Number 0, Number (-3)] $ \actual ->-    check Integer actual >>= assertEqual []-  for_ [Number 5000, Number 0] $ \actual ->-    check NonNegativeInteger actual >>= assertEqual []-  check NonNegativeInteger (Number (-3)) >>= assertEqual (mismatch NonNegativeInteger (Number (-3)))-  for_ [Integer, NonNegativeInteger] $ \fieldFormat ->-    for_ [String "5000", Number 5.5, Bool True] $ \actual ->-      check fieldFormat actual >>= assertEqual (mismatch fieldFormat actual)-  for_ [Bool True, Bool False] $ \actual ->-    check Boolean actual >>= assertEqual []-  for_ [String "true", Number 1] $ \actual ->-    check Boolean actual >>= assertEqual (mismatch Boolean actual)-  -- A list is a list of values, so a format constrains each element. The-  -- cardinality has to be declared, because a numeric format alone refines an-  -- unspecified one to scalar.-  let integers = toJSON ([1, 2, 3] :: [Int])-      mixed = toJSON ([Number 1, String "2"] :: [Value])-  checkWith List Integer integers >>= assertEqual []-  checkWith List Integer mixed >>= assertEqual (mismatch Integer mixed)---- | Declaring a non-textual format and no cardinality refines the rule to--- 'Scalar'. Without the refinement the 'Any' cardinality routes presence through--- the legacy predicate, which counts only non-empty text and non-empty arrays,--- so a present @usage_count: 5000@ is reported /missing/ before its value is--- ever examined. An explicitly declared cardinality still wins.-testNonTextualFormatRefinesCardinality :: Either Text ()-testNonTextualFormatRefinesCardinality = do-  cid <- parseTestConceptId "counted"-  let specWith cardinality fieldFormat =-        typeAwareProfileSpec-          { frontmatter =-              FrontmatterRules-                { required =-                    [ fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing,-                      fieldRule "usage_count" Nothing [] cardinality (Just fieldFormat) Nothing Nothing Nothing-                    ],-                  recommended = [],-                  optional = []-                },-            allowUnknownTypes = True,-            types = []-          }-      check cardinality fieldFormat actual = do-        compiled <- firstShow (compileProfile (specWith cardinality fieldFormat))-        concept <--          profileConcept "counted" [("type", String "Extension"), ("usage_count", actual)] "# Counted\n"-        pure (validateProfile PermissiveConformance compiled [concept])-  for_ [NonNegativeInteger, Integer] $ \fieldFormat ->-    check Any fieldFormat (Number 5000) >>= assertEqual []-  check Any Boolean (Bool False) >>= assertEqual []-  -- The gap this closes: a textual format leaves the rule at 'Any', where a-  -- number still does not count as present. The value check runs regardless of-  -- the presence verdict, so both violations are reported.-  check Any Rfc3339Utc (Number 5000)-    >>= assertEqual-      [ MissingProfileField cid "usage_count" Nothing,-        ValueFormatMismatch cid (fieldPath "usage_count") Rfc3339Utc (Number 5000)-      ]-  -- An explicit cardinality wins, and a list of integers stays coherent rather-  -- than becoming an error.-  let integers = toJSON ([1, 2] :: [Int])-  check List NonNegativeInteger integers >>= assertEqual []-  check Scalar NonNegativeInteger integers-    >>= assertEqual [CardinalityMismatch cid (fieldPath "usage_count") Scalar integers]---- | The two new narrowing pairs, checked the way the 'Uri'/'UriWithScheme' pair--- is: a profile-scope format and a narrower type-scope one compile to the--- narrower rule rather than to a 'ConflictingFieldFormat'.-testNewFormatsNarrowAcrossScopes :: Either Text ()-testNewFormatsNarrowAcrossScopes = do-  cid <- parseTestConceptId "narrowing"-  let baseType = firstTypeRule typeAwareProfileSpec-      profileWith profileFormat typeFormat =-        typeAwareProfileSpec-          { -- v0.2, for the same reason 'singleFormatProfile' is: the narrowing-            -- pairs under test include the actor formats.-            okfVersion = "0.2",-            frontmatter =-              FrontmatterRules-                { required =-                    [ fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing,-                      fieldRule "value" Nothing [] Any (Just profileFormat) Nothing Nothing Nothing-                    ],-                  recommended = [],-                  optional = []-                },-            types =-              [ withTypeFrontmatter-                  FrontmatterRules-                    { required = [fieldRule "value" Nothing [] Any (Just typeFormat) Nothing Nothing Nothing],-                      recommended = [],-                      optional = []-                    }-                  baseType-              ]-          }-      check profileFormat typeFormat actual = do-        compiled <- firstShow (compileProfile (profileWith profileFormat typeFormat))-        concept <--          profileConcept "narrowing" [("type", String "Owned Concept"), ("value", actual)] "# Narrowing\n"-        pure (validateProfile PermissiveConformance compiled [concept])-  for_ [(Actor, Profile.HumanActor), (Profile.HumanActor, Actor)] $ \(wide, narrow) -> do-    check wide narrow (String "human:ahormati") >>= assertEqual []-    check wide narrow (String "process:nightly")-      >>= assertEqual-        [ValueFormatMismatch cid (fieldPath "value") Profile.HumanActor (String "process:nightly")]-  for_ [(Integer, NonNegativeInteger), (NonNegativeInteger, Integer)] $ \(wide, narrow) -> do-    check wide narrow (Number 5000) >>= assertEqual []-    check wide narrow (Number (-3))-      >>= assertEqual-        [ValueFormatMismatch cid (fieldPath "value") NonNegativeInteger (Number (-3))]-  assertEqual-    (Left (ConflictingFieldFormat (fieldPath "value") Actor Integer :| []))-    (compileProfile (profileWith Actor Integer))---- | Declares @okfVersion = "0.2"@ rather than inheriting 'typeAwareProfileSpec'\'s--- @"0.1"@, because the formats under test include the OKF v0.2 actor--- convention, and 'compileProfile' rejects a v0.2 format under a v0.1--- declaration.-singleFormatProfile :: Cardinality -> FieldFormat -> ProfileSpec-singleFormatProfile cardinality fieldFormat =-  typeAwareProfileSpec-    { okfVersion = "0.2",-      frontmatter =-        FrontmatterRules-          { required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing],-            recommended = [fieldRule "value" Nothing [] cardinality (Just fieldFormat) Nothing Nothing Nothing],-            optional = []-          },-      allowUnknownTypes = True,-      types = []-    }--singleCardinalityProfile :: Bool -> Cardinality -> [Text] -> ProfileSpec-singleCardinalityProfile isRequired cardinality allowed =-  typeAwareProfileSpec-    { frontmatter =-        FrontmatterRules-          { required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing] <> [rule | isRequired],-            recommended = [rule | not isRequired],-            optional = []-          },-      allowUnknownTypes = True,-      types = []-    }-  where-    rule = fieldRule "value" Nothing allowed cardinality Nothing Nothing Nothing Nothing--testCompiledNestedRules :: Either Text ()-testCompiledNestedRules = do-  let profileRules =-        NestedRules-          { required = [nestedFieldRule "kind" Nothing ["decision", "implementation"] Any Nothing Nothing Nothing],-            recommended = [nestedFieldRule "notes" Nothing [] Scalar Nothing Nothing Nothing],-            optional = []-          }-      typeRules =-        NestedRules-          { required =-              [ nestedFieldRule "kind" Nothing ["implementation", "operations"] Any Nothing Nothing Nothing,-                nestedFieldRule "outcome" Nothing ["approved", "rejected"] Any Nothing Nothing Nothing-              ],-            recommended = [],-            optional = []-          }-      base = nestedProfileWithRules Any profileRules (Just typeRules)-  compiled <- firstShow (compileProfile base)-  concept <--    profileConcept-      "reviewed/merge"-      [ ("type", String "Reviewed Concept"),-        ( "reviews",-          toJSON-            [ object-                [ "kind" .= ("decision" :: Text),-                  "outcome" .= ("approved" :: Text)-                ]-            ]-        )-      ]-      "# Merge\n"-  cid <- parseTestConceptId "reviewed/merge"-  assertEqual-    [ ValueNotInVocabulary-        cid-        (nestedTestPath 0 "kind")-        ["implementation"]-        (String "decision")-    ]-    (validateProfile PermissiveConformance compiled [concept])-  let impossible = nestedProfileWithRules Scalar profileRules Nothing-  assertEqual-    (Left (ElementFieldsRequireList Nothing (fieldPath "reviews") Scalar :| []))-    (compileProfile impossible)--testNestedRecordValidation :: Either Text ()-testNestedRecordValidation = do-  compiled <- firstShow (compileProfile nestedReviewProfileSpec)-  let firstReview =-        object-          [ "kind" .= ("human" :: Text),-            "reviewer" .= ("Ari" :: Text),-            "reviewed_at" .= ("2026-07-29T16:00:00Z" :: Text),-            "document_timestamp" .= ("2026-07-29T17:00:00Z" :: Text),-            "scope" .= ("content" :: Text),-            "outcome" .= ("approved" :: Text),-            "context" .= ("Complete" :: Text),-            "notes" .= ("No blockers" :: Text),-            "provider" .= ("allowed-extra-key" :: Text)-          ]-      thirdReview =-        object-          [ "kind" .= ("model" :: Text),-            "reviewer" .= ("Bo" :: Text),-            "reviewed_at" .= ("2026-13-45T99:99:99Z" :: Text),-            "document_timestamp" .= ("2026-07-29T17:00:00Z" :: Text),-            "scope" .= ("invalid" :: Text),-            "context" .= (["wrong"] :: [Text])-          ]-      reviewValues = toJSON [firstReview, String "not-a-record", thirdReview]-  concept <--    profileConcept-      "reviewed/bad"-      [("type", String "Reviewed Concept"), ("reviews", reviewValues)]-      "# Bad\n"-  cid <- parseTestConceptId "reviewed/bad"-  let permissiveExpected =-        [ NestedElementNotRecord cid (FieldPath (FieldName "reviews" :| [ArrayIndex 1])) (String "not-a-record"),-          CardinalityMismatch cid (nestedTestPath 2 "context") Scalar (toJSON (["wrong"] :: [Text])),-          MissingNestedProfileField cid (nestedTestPath 2 "outcome") Nothing,-          ValueFormatMismatch cid (nestedTestPath 2 "reviewed_at") Rfc3339Utc (String "2026-13-45T99:99:99Z"),-          ValueNotInVocabulary cid (nestedTestPath 2 "scope") reviewScopes (String "invalid")-        ]-  assertEqual permissiveExpected (validateProfile PermissiveConformance compiled [concept])-  assertEqual-    [ NestedElementNotRecord cid (FieldPath (FieldName "reviews" :| [ArrayIndex 1])) (String "not-a-record"),-      CardinalityMismatch cid (nestedTestPath 2 "context") Scalar (toJSON (["wrong"] :: [Text])),-      MissingRecommendedNestedProfileField cid (nestedTestPath 2 "notes") Nothing,-      MissingNestedProfileField cid (nestedTestPath 2 "outcome") Nothing,-      ValueFormatMismatch cid (nestedTestPath 2 "reviewed_at") Rfc3339Utc (String "2026-13-45T99:99:99Z"),-      ValueNotInVocabulary cid (nestedTestPath 2 "scope") reviewScopes (String "invalid")-    ]-    (validateProfile StrictAuthoring compiled [concept])--nestedProfileWithRules :: Cardinality -> NestedRules -> Maybe NestedRules -> ProfileSpec-nestedProfileWithRules outerCardinality profileNested typeNested =-  ProfileSpec-    { name = "nested-merge",-      description = Nothing,-      guidance = Nothing,-      okfVersion = "0.1",-      frontmatter =-        FrontmatterRules-          { required =-              [ requiredField "type",-                fieldRule "reviews" Nothing [] outerCardinality Nothing (Just profileNested) Nothing Nothing-              ],-            recommended = [],-            optional = []-          },-      allowUnknownTypes = False,-      allowUnknownFields = True,-      idField = Nothing,-      requireBundleVersion = Nothing,-      types =-        [ TypeRule-            { type_ = "Reviewed Concept",-              description = Nothing,-              guidance = Nothing,-              frontmatter =-                FrontmatterRules-                  { required = maybe [] (\rules -> [fieldRule "reviews" Nothing [] Any Nothing (Just rules) Nothing Nothing]) typeNested,-                    recommended = [],-                    optional = []-                  },-              pathPattern = Nothing,-              resourceScheme = Nothing,-              requireSchemaSection = False,-              schemaColumns = [],-              idPrefix = Nothing-            }-        ]-    }--nestedReviewProfileSpec :: ProfileSpec-nestedReviewProfileSpec =-  nestedProfileWithRules Any nestedRules Nothing-  where-    nestedRules =-      NestedRules-        { required =-            [ nestedFieldRule "kind" Nothing ["human", "model"] Any Nothing Nothing Nothing,-              nestedFieldRule "reviewer" Nothing [] Scalar Nothing Nothing Nothing,-              nestedFieldRule "reviewed_at" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing,-              nestedFieldRule "document_timestamp" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing,-              nestedFieldRule "scope" Nothing reviewScopes Any Nothing Nothing Nothing,-              nestedFieldRule "outcome" Nothing ["approved", "changes-requested", "commented"] Any Nothing Nothing Nothing,-              nestedFieldRule "context" Nothing [] Scalar Nothing Nothing Nothing-            ],-          recommended = [nestedFieldRule "notes" Nothing [] Scalar Nothing Nothing Nothing],-          optional = []-        }--nestedTestPath :: Int -> Text -> FieldPath-nestedTestPath elementIndex key =-  FieldPath (FieldName "reviews" :| [ArrayIndex elementIndex, FieldName key])---- | A profile whose single object-valued key carries the given member rules and--- the given declared cardinality. Built with record syntax rather than the--- positional 'fieldRule' helper precisely because @objectFields@ is the member--- under test here.-objectProfileWithRules :: Text -> Cardinality -> Maybe NestedRules -> Maybe NestedRules -> ProfileSpec-objectProfileWithRules key declaredCardinality objectRules elementRules =-  ProfileSpec-    { name = "object-rules",-      description = Nothing,-      guidance = Nothing,-      okfVersion = "0.1",-      frontmatter =-        FrontmatterRules-          { required =-              [ requiredField "type",-                FieldRule-                  { field = key,-                    description = Nothing,-                    allowedValues = [],-                    cardinality = declaredCardinality,-                    format = Nothing,-                    elementFields = elementRules,-                    objectFields = objectRules,-                    reference = Nothing,-                    path = Nothing,-                    when = Nothing,-                    uniqueBy = Nothing-                  }-              ],-            recommended = [],-            optional = []-          },-      allowUnknownTypes = True,-      allowUnknownFields = True,-      idField = Nothing,-      requireBundleVersion = Nothing,-      types = []-    }---- | The member rules used by the object-rule tests: @by@ is demanded, @at@ is--- recommended and must be an RFC3339 UTC timestamp.-provenanceMemberRules :: NestedRules-provenanceMemberRules =-  NestedRules-    { required = [nestedFieldRule "by" (Just "Who or what produced this content.") [] Any Nothing Nothing Nothing],-      recommended = [nestedFieldRule "at" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing],-      optional = []-    }---- | Declaring @objectFields@ next to an explicit scalar or list cardinality is--- incoherent — a mapping is neither — and is rejected at compile time in both--- directions, mirroring 'ElementFieldsRequireList' for the opposite mistake.-testObjectFieldsRequireObjectShape :: Either Text ()-testObjectFieldsRequireObjectShape = do-  assertEqual-    (Left (ObjectFieldsRequireObjectShape Nothing (fieldPath "generated") List :| []))-    (compileProfile (objectProfileWithRules "generated" List (Just provenanceMemberRules) Nothing))-  assertEqual-    (Left (ObjectFieldsRequireObjectShape Nothing (fieldPath "generated") Scalar :| []))-    (compileProfile (objectProfileWithRules "generated" Scalar (Just provenanceMemberRules) Nothing))---- | A rule that declares object members and no explicit cardinality is refined--- to 'Object', the compiled-only cardinality that has no Dhall spelling, and its--- members are reachable through the new accessor.-testCompileObjectRule :: Either Text ()-testCompileObjectRule = do-  compiled <--    firstShow-      (compileProfile (objectProfileWithRules "generated" Any (Just provenanceMemberRules) Nothing))-  rule <- lookupBaseRule compiled "generated"-  assertEqual Object (fieldRuleCardinality rule)-  assertEqual Nothing (fieldRuleElementFields rule)-  case fieldRuleObjectFields rule of-    Nothing -> Left "expected compiled object member rules"-    Just members -> do-      assertEqual ["at", "by"] (Map.keys members)-      byRule <- maybe (Left "expected a rule for by") Right (Map.lookup "by" members)-      assertEqual-        (Just "Who or what produced this content.")-        (fieldRuleDescription byRule)-      assertEqual [RequiredField] (map presenceClauseRequirement (fieldRulePresenceClauses byRule))-      -- Depth-bounded: a member rule never itself carries a nested shape.-      assertEqual Nothing (fieldRuleObjectFields byRule)-      assertEqual Nothing (fieldRuleElementFields byRule)---- | A rule declaring both shapes stays at 'Any' cardinality, which is what lets--- either OKF v0.2 spelling of @verified@ satisfy it, and compiles the same--- member rules under both accessors.-testCompileRecordOrListRule :: Either Text ()-testCompileRecordOrListRule = do-  compiled <--    firstShow-      ( compileProfile-          (objectProfileWithRules "verified" Any (Just provenanceMemberRules) (Just provenanceMemberRules))-      )-  rule <- lookupBaseRule compiled "verified"-  assertEqual Any (fieldRuleCardinality rule)-  assertEqual (Just ["at", "by"]) (Map.keys <$> fieldRuleObjectFields rule)-  assertEqual (Just ["at", "by"]) (Map.keys <$> fieldRuleElementFields rule)---- | A profile with one path rule on a top-level key, plus the given rules on the--- same key at type scope, so scheme intersection across scopes is exercisable.-pathProfileWith :: Maybe PathReferenceRule -> Maybe FieldFormat -> Maybe HandleReferenceRule -> Maybe PathReferenceRule -> ProfileSpec-pathProfileWith profilePath declaredFormat handlePolicy typePath =-  ProfileSpec-    { name = "path-rules",-      description = Nothing,-      guidance = Nothing,-      okfVersion = "0.1",-      frontmatter =-        FrontmatterRules-          { required = [requiredField "type"],-            recommended = [],-            -- Optional rather than required, so a concept that simply does not-            -- carry the key reports nothing and the tests below see only the-            -- value checks they are about. An optional rule is fully-            -- value-checked whenever it is present.-            optional =-              [ (requiredField "resource")-                  { format = declaredFormat,-                    reference = handlePolicy,-                    path = profilePath-                  }-              ]-          },-      allowUnknownTypes = True,-      allowUnknownFields = True,-      idField = if isJust handlePolicy then Just "docId" else Nothing,-      requireBundleVersion = Nothing,-      types =-        [ TypeRule-            { type_ = "Metric",-              description = Nothing,-              guidance = Nothing,-              frontmatter =-                FrontmatterRules-                  { required = [],-                    recommended = [],-                    optional = [(requiredField "resource") {path = typePath}]-                  },-              pathPattern = Nothing,-              resourceScheme = Nothing,-              requireSchemaSection = False,-              schemaColumns = [],-              idPrefix = if isJust handlePolicy then Just "ADR" else Nothing-            }-        | isJust typePath || isJust handlePolicy-        ]-    }---- | A profile whose @sources@ key is a list of records, each of which carries a--- path rule on @resource@ — the OKF v0.2 §6.2 field the rule kind exists for,--- and the one that was unreachable before nested path checking existed.-sourcesPathProfile :: [Text] -> ProfileSpec-sourcesPathProfile permittedSchemes =-  ProfileSpec-    { name = "sources-paths",-      description = Nothing,-      guidance = Nothing,-      okfVersion = "0.1",-      frontmatter =-        FrontmatterRules-          { required = [requiredField "type"],-            recommended = [],-            -- Optional for the same reason 'pathProfileWith' is: the tests are-            -- about what a present value resolves to, not about presence.-            optional = [fieldRule "sources" Nothing [] List Nothing (Just memberRules) Nothing Nothing]-          },-      allowUnknownTypes = True,-      allowUnknownFields = True,-      idField = Nothing,-      requireBundleVersion = Nothing,-      types = []-    }-  where-    memberRules =-      NestedRules-        { required =-            [ (nestedFieldRule "resource" Nothing [] Any Nothing Nothing Nothing)-                { path = Just (PathReferenceRule permittedSchemes False)-                }-            ],-          recommended = [],-          optional = []-        }---- | Compiling a path rule normalizes its scheme list exactly as a handle rule's--- is — deduplicated case-insensitively and case-folded for storage — and the--- result is reachable through the new accessor at top-level, nested, and object--- scope. Nested reachability is the part with no precedent:--- 'compileOptionalNestedFieldRule' previously hard-coded every reference member--- to 'Nothing'.-testCompilePathRule :: Either Text ()-testCompilePathRule = do-  compiled <--    firstShow-      (compileProfile (pathProfileWith (Just (PathReferenceRule ["HTTPS", "https", "mori"] True)) Nothing Nothing Nothing))-  rule <- lookupBaseRule compiled "resource"-  assertEqual (Just (PathReferenceRule ["https", "mori"] True)) (fieldRulePath rule)-  -- A path rule and a handle rule are different things and never both present.-  assertEqual Nothing (fieldRuleReference rule)-  nestedCompiled <- firstShow (compileProfile (sourcesPathProfile ["https"]))-  sourcesRule <- lookupBaseRule nestedCompiled "sources"-  case fieldRuleElementFields sourcesRule of-    Nothing -> Left "expected compiled element member rules for sources"-    Just members -> do-      memberRule <- maybe (Left "expected a rule for resource") Right (Map.lookup "resource" members)-      assertEqual (Just (PathReferenceRule ["https"] False)) (fieldRulePath memberRule)-      -- Nested rules stay depth-bounded and carry no handle policy at all.-      assertEqual Nothing (fieldRuleReference memberRule)---- | A type-scope path rule narrows the profile-scope one rather than replacing--- it: schemes intersect and @allowSelf@ combines with logical AND. Unlike--- 'mergeReferenceRule' the merge is total, because a path policy has no--- @localPrefix@ for two scopes to disagree about.-testMergePathRule :: Either Text ()-testMergePathRule = do-  compiled <--    firstShow-      ( compileProfile-          ( pathProfileWith-              (Just (PathReferenceRule ["https", "mori"] True))-              Nothing-              Nothing-              (Just (PathReferenceRule ["mori", "ftp"] False))-          )-      )-  merged <- lookupCompiledRule "resource" (compiledProfileRulesForType compiled "Metric")-  assertEqual (Just (PathReferenceRule ["mori"] False)) (fieldRulePath merged)---- | The three ways a path rule can be incoherent on its own. Two reuse the--- handle-reference definition errors because the claim is identical; the third--- is new, and cannot arise at nested scope where 'NestedFieldRule' carries no--- handle policy.-testPathDefinitionErrors :: Either Text ()-testPathDefinitionErrors = do-  -- A value cannot be resolved as both a PREFIX-N handle and a §6.2 path.-  assertEqual-    (Left (PathReferenceWithHandleReference Nothing (fieldPath "resource") :| []))-    ( compileProfile-        ( pathProfileWith-            (Just (PathReferenceRule [] False))-            Nothing-            (Just (handleReferenceRule "ADR" [] False))-            Nothing-        )-    )-  -- A scheme that is not a legal URI scheme, at top-level scope.-  assertEqual-    (Left (InvalidExternalReferenceScheme Nothing (fieldPath "resource") "9nope" :| []))-    (compileProfile (pathProfileWith (Just (PathReferenceRule ["9nope"] False)) Nothing Nothing Nothing))-  -- The same mistake at nested scope, which the reference walk did not reach-  -- before this plan extended it.-  assertEqual-    (Left (InvalidExternalReferenceScheme Nothing (objectMemberPath "sources" "resource") "9nope" :| []))-    (compileProfile (sourcesPathProfile ["9nope"]))-  -- A named format would be checked against text the path rule is already-  -- interpreting structurally, and the two can contradict.-  assertEqual-    (Left (ReferenceWithFormat Nothing (fieldPath "resource") Uri :| []))-    (compileProfile (pathProfileWith (Just (PathReferenceRule [] False)) (Just Uri) Nothing Nothing))---- | The five outcomes of checking one path value at top-level scope, plus the--- two shapes that are accepted in silence. Every diagnostic carries the raw text--- the author wrote rather than the collapsed path okf computed from it.-testValidatePathTopLevel :: Either Text ()-testValidatePathTopLevel = do-  compiled <--    firstShow-      (compileProfile (pathProfileWith (Just (PathReferenceRule ["https"] False)) Nothing Nothing Nothing))-  cid <- parseTestConceptId "metrics/revenue"-  target <- profileConcept "references/policy" [("type", String "Reference")] "# Policy\n"-  let check value = do-        subject <--          profileConcept-            "metrics/revenue"-            [("type", String "Metric"), ("resource", value)]-            "# Revenue\n"-        pure (validateProfile PermissiveConformance compiled [subject, target])-      resourcePath = fieldPath "resource"-  -- A bundle path naming a real concept, and a permitted external URL, are both-  -- silent.-  check (String "/references/policy.md") >>= assertEqual []-  check (String "../references/policy.md") >>= assertEqual []-  check (String "https://wiki.acme/revenue") >>= assertEqual []-  -- A path to a non-Markdown file is accepted without a check, because-  -- validateProfile is handed concepts and never looked. §6.3's own example.-  check (String "/references/attesters/revenue.py") >>= assertEqual []-  -- The four failures.-  check (String "/references/gone.md")-    >>= assertEqual [DanglingPathReference cid resourcePath "/references/gone.md"]-  check (String "ftp://files.acme/revenue.csv")-    >>= assertEqual [ExternalReferenceSchemeNotAllowed cid resourcePath "ftp" ["https"]]-  check (String "../../../etc/passwd")-    >>= assertEqual [PathEscapesBundle cid resourcePath "../../../etc/passwd"]-  check (String "   ")-    >>= assertEqual [MalformedPathReference cid resourcePath (String "   ")]-  -- A value that is not text at all is malformed rather than silently skipped.-  check (Bool True)-    >>= assertEqual [MalformedPathReference cid resourcePath (Bool True)]-  -- A path resolving to the concept that carries it, with allowSelf unset.-  check (String "/metrics/revenue.md")-    >>= assertEqual [SelfDocumentReference cid resourcePath "/metrics/revenue.md"]---- | The core-versus-profile divergence, closed: 'validateProfileWith' resolves a--- path naming a file that is not a concept, and 'validateProfile' still cannot--- and still says nothing.------ Run against a real directory because that is the only way to have an inventory--- holding a file 'walkBundle' filters out. @dangling-frontmatter-path@ carries--- both halves already: @non-markdown.md@ names a @.py@ that is there and--- @dangling.md@ names a @.txt@ that is not.------ Specification §6.3's example is exactly this shape, and--- @docs\/adr\/13-the-references-convention-and-non-markdown-files.md@ records why--- the silent answer is preserved rather than tightened: a caller with no--- directory has not looked, and reporting a target it never checked would be a--- claim okf cannot back.-testValidateProfileWithInventory :: IO (Either Text ())-testValidateProfileWithInventory = do-  root <- fixturePath "dangling-frontmatter-path"-  concepts <- readBundle root-  inventory <- readBundleInventory root-  pure-    ( do-        compiled <--          firstShow-            ( compileProfile-                (pathProfileWith (Just (PathReferenceRule ["bigquery"] False)) Nothing Nothing Nothing)-            )-        danglingId <- firstShow (parseConceptId "dangling")-        specSpellingId <- firstShow (parseConceptId "computations/spec-spelling")-        let resourcePath = fieldPath "resource"-        -- With the full inventory: the missing .txt and the relative .py that-        -- resolves outside the bundle are both reported, and the .py that is-        -- really there is silent.-        assertEqual-          [ DanglingPathReference specSpellingId resourcePath "references/attesters/revenue.py",-            DanglingPathReference danglingId resourcePath "/references/deleted.txt"-          ]-          (validateProfileWith inventory PermissiveConformance compiled concepts)-        -- Without it: nothing at all, exactly as before this plan. Neither target-        -- is Markdown, so a concepts-only caller has not looked at either.-        assertEqual [] (validateProfile PermissiveConformance compiled concepts)-    )---- | The specification §10 contract expressed as a house convention, run against--- the bundle it was written for.------ This is the descriptor @docs\/user\/profiles.md@ shows, and this test is what--- stops that document's transcript from rotting: the descriptor must keep--- compiling ('testFrozenFixturesCompile' lists it) and must keep reporting these--- deviations and no others.------ What it demonstrates is the boundary this whole initiative rests on. okf's core--- enforces exactly §10.2's one REQUIRED field and §10.3's exactly-one rule;--- everything below — that a parameter carry a @type@, that an executor be--- declared at all — is a team's own policy, reached with @objectFields@ for the--- mapping-valued keys and @elementFields@ for the list-valued one, and scoped to--- one @type@ with a 'TypeRule' so no @Metric@ in the bundle is asked for a--- @runtime@.------ @computations\/churn@ is the concept that makes the point: it produces no core--- diagnostic at all and one deviation here.-testAttestedComputationHouseProfile :: IO (Either Text ())-testAttestedComputationHouseProfile = do-  descriptorPath <- fixtureFilePath "profiles/attested-computation-house.dhall"-  loaded <- loadProfileFile descriptorPath-  root <- fixturePath "attested-computation"-  concepts <- readBundle root-  inventory <- readBundleInventory root-  pure $ case loaded of-    Left err -> Left ("failed to load the house attested computation profile: " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      bothId <- firstShow (parseConceptId "computations/both-computations")-      churnId <- firstShow (parseConceptId "computations/churn")-      marginId <- firstShow (parseConceptId "computations/margin")-      noneId <- firstShow (parseConceptId "computations/no-computation")-      twoBlocksId <- firstShow (parseConceptId "computations/two-blocks")-      -- Only the required rules fire in permissive mode. `computations/revenue`-      -- carries the whole contract and is absent from both lists.-      assertEqual-        [ MissingProfileField bothId "executor" Nothing,-          MissingProfileField bothId "parameters" Nothing,-          MissingNestedProfileField churnId parameterTypePath Nothing,-          MissingProfileField marginId "executor" Nothing,-          MissingProfileField noneId "executor" Nothing,-          MissingProfileField noneId "parameters" Nothing,-          MissingProfileField twoBlocksId "executor" Nothing,-          MissingProfileField twoBlocksId "parameters" Nothing-        ]-        (validateProfileWith inventory PermissiveConformance compiled concepts)-      -- Under strict the recommended rules join them, including the nested-      -- `executor.receipt` on the one concept that declares an executor without-      -- one. No path deviation appears in either list: every path-valued field in-      -- this bundle resolves.-      assertEqual-        [ MissingRecommendedProfileField bothId "attester" Nothing,-          MissingProfileField bothId "executor" Nothing,-          MissingProfileField bothId "parameters" Nothing,-          MissingRecommendedProfileField churnId "attester" Nothing,-          MissingRecommendedNestedProfileField churnId executorReceiptPath Nothing,-          MissingNestedProfileField churnId parameterTypePath Nothing,-          MissingRecommendedProfileField marginId "attester" Nothing,-          MissingProfileField marginId "executor" Nothing,-          MissingRecommendedProfileField noneId "attester" Nothing,-          MissingProfileField noneId "executor" Nothing,-          MissingProfileField noneId "parameters" Nothing,-          MissingRecommendedProfileField twoBlocksId "attester" Nothing,-          MissingProfileField twoBlocksId "executor" Nothing,-          MissingProfileField twoBlocksId "parameters" Nothing-        ]-        (validateProfileWith inventory StrictAuthoring compiled concepts)-  where-    parameterTypePath = FieldPath (FieldName "parameters" :| [ArrayIndex 0, FieldName "type"])-    executorReceiptPath = FieldPath (FieldName "executor" :| [FieldName "receipt"])---- | The motivating case: a path rule on @sources[].resource@, reported with the--- element index so the author can find the entry. Nested path checking did not--- exist before this plan — 'NestedFieldRule' had no reference member of any kind--- — so this is the assertion the whole plan is for.-testValidatePathNested :: Either Text ()-testValidatePathNested = do-  compiled <- firstShow (compileProfile (sourcesPathProfile ["https"]))-  cid <- parseTestConceptId "metric"-  target <- profileConcept "references/policy" [("type", String "Reference")] "# Policy\n"-  subject <--    profileConcept-      "metric"-      [ ("type", String "Metric"),-        ( "sources",-          toJSON-            [ object ["id" .= ("policy" :: Text), "resource" .= ("/references/policy.md" :: Text)],-              object ["id" .= ("gone" :: Text), "resource" .= ("/references/gone.md" :: Text)],-              object ["id" .= ("upstream" :: Text), "resource" .= ("https://wiki.acme/revenue" :: Text)],-              object ["id" .= ("ftp" :: Text), "resource" .= ("ftp://files.acme/revenue.csv" :: Text)],-              object ["id" .= ("escape" :: Text), "resource" .= ("../../etc/passwd" :: Text)],-              object ["id" .= ("script" :: Text), "resource" .= ("references/attesters/revenue.py" :: Text)]-            ]-        )-      ]-      "# Revenue\n"-  assertEqual-    [ DanglingPathReference cid (nestedTestPathIn "sources" 1 "resource") "/references/gone.md",-      ExternalReferenceSchemeNotAllowed cid (nestedTestPathIn "sources" 3 "resource") "ftp" ["https"],-      PathEscapesBundle cid (nestedTestPathIn "sources" 4 "resource") "../../etc/passwd"-    ]-    (validateProfile PermissiveConformance compiled [subject, target])---- | The same rule kind at object scope, where the member is named without an--- index: @executor.resource@ rather than @executor[0].resource@.-testValidatePathObjectScope :: Either Text ()-testValidatePathObjectScope = do-  compiled <--    firstShow-      ( compileProfile-          ( objectProfileWithRules-              "executor"-              Any-              ( Just-                  NestedRules-                    { required =-                        [ (nestedFieldRule "resource" Nothing [] Any Nothing Nothing Nothing)-                            { path = Just (PathReferenceRule [] False)-                            }-                        ],-                      recommended = [],-                      optional = []-                    }-              )-              Nothing-          )-      )-  cid <- parseTestConceptId "thing"-  subject <--    profileConcept-      "thing"-      [("type", String "Thing"), ("executor", object ["resource" .= ("/computations/gone.md" :: Text)])]-      "# Thing\n"-  assertEqual-    [DanglingPathReference cid (objectMemberPath "executor" "resource") "/computations/gone.md"]-    (validateProfile PermissiveConformance compiled [subject])--nestedTestPathIn :: Text -> Int -> Text -> FieldPath-nestedTestPathIn parent elementIndex key =-  FieldPath (FieldName parent :| [ArrayIndex elementIndex, FieldName key])---- | A profile declaring the given @okfVersion@, with the given rules in the--- given presence list, so the version checks can be exercised in one shape.-versionProfileWith :: Text -> Text -> [FieldRule] -> ProfileSpec-versionProfileWith declaredVersion listName rules =-  ProfileSpec-    { name = "versioned",-      description = Nothing,-      guidance = Nothing,-      okfVersion = declaredVersion,-      frontmatter =-        FrontmatterRules-          { required = [requiredField "type"] <> [rule | rule <- rules, listName == "required"],-            recommended = [rule | rule <- rules, listName == "recommended"],-            optional = [rule | rule <- rules, listName == "optional"]-          },-      allowUnknownTypes = True,-      allowUnknownFields = True,-      idField = Nothing,-      requireBundleVersion = Nothing,-      types = []-    }---- | An @okfVersion@ okf cannot read at all, and one naming a major version okf--- does not implement. The second deliberately diverges from the bundle-side rule--- of specification §12: a bundle may come from a third party and is read--- best-effort, while a profile is an instruction to okf whose author is present.-testProfileVersionParsing :: Either Text ()-testProfileVersionParsing = do-  assertEqual-    (Left (InvalidProfileOkfVersion "banana" :| []))-    (compileProfile (versionProfileWith "banana" "optional" []))-  assertEqual-    (Left (ProfileOkfVersionNotUnderstood "1.0" :| []))-    (compileProfile (versionProfileWith "1.0" "optional" []))---- | A higher /minor/ within a known major is clamped rather than rejected,--- mirroring 'Okf.Validation.versionGate': §12 defines a minor bump as--- backward-compatible additions, so a v0.9 profile expresses only rules okf--- already understands. The clamp is observable through the diagnostic, which--- names the effective version rather than the declared one.-testProfileVersionMinorClamp :: Either Text ()-testProfileVersionMinorClamp = do-  let timestampRule = fieldRule "timestamp" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing Nothing-  assertEqual-    (Left (FieldSupersededInOkfVersion Nothing (fieldPath "timestamp") "0.2" "0.2" :| []))-    (compileProfile (versionProfileWith "0.9" "recommended" [timestampRule]))-  -- And a v0.9 profile that names nothing version-specific simply compiles.-  case compileProfile (versionProfileWith "0.9" "optional" []) of-    Left errs -> Left ("expected a v0.9 profile to compile, got " <> Text.pack (show (toList errs)))-    Right _ -> Right ()---- | A profile that demands a bundle version okf cannot parse is rejected at--- compile time, before any bundle is read: no declaration could ever be compared--- against it, so the descriptor is asking for something unanswerable.------ An unknown /major/ is deliberately accepted here, unlike in @okfVersion@. There--- the profile asks okf to interpret rules it may not understand; here it states a--- minimum that a bundle's own declaration is compared against, which stays--- meaningful whatever the major is.-testRequiredBundleVersionParsing :: Either Text ()-testRequiredBundleVersionParsing = do-  assertEqual-    (Left (InvalidRequiredBundleVersion "banana" :| []))-    (compileProfile (requireBundleVersionProfile (Just "banana")))-  for_ [Just "0.2", Just "1.0", Nothing] $ \required ->-    case compileProfile (requireBundleVersionProfile required) of-      Left errs -> Left ("expected a clean compile, got " <> Text.pack (show (toList errs)))-      Right _ -> Right ()---- | What each shape of a bundle's §12 declaration means against a profile that--- requires 0.2. A bundle ahead of the minimum is not a deviation; one behind it,--- one that says nothing, and one okf cannot parse all are.-testValidateProfileVersion :: Either Text ()-testValidateProfileVersion = do-  compiled <- firstShow (compileProfile (requireBundleVersionProfile (Just "0.2")))-  assertEqual [] (validateProfileVersion (VersionDeclared (OkfVersion 0 2)) compiled)-  assertEqual [] (validateProfileVersion (VersionDeclared (OkfVersion 0 3)) compiled)-  assertEqual [] (validateProfileVersion (VersionDeclared (OkfVersion 1 0)) compiled)-  assertEqual-    [RequiredBundleVersionUnmet "0.2" (Just "0.1")]-    (validateProfileVersion (VersionDeclared (OkfVersion 0 1)) compiled)-  assertEqual-    [RequiredBundleVersionUnmet "0.2" Nothing]-    (validateProfileVersion VersionUndeclared compiled)-  assertEqual-    [RequiredBundleVersionUnmet "0.2" (Just "banana")]-    (validateProfileVersion (VersionUnparseable "banana") compiled)---- | The default is inert: a profile that requires nothing reports nothing,--- whatever the bundle declares. Almost every profile is this one.-testValidateProfileVersionUnrequired :: Either Text ()-testValidateProfileVersionUnrequired = do-  compiled <- firstShow (compileProfile (requireBundleVersionProfile Nothing))-  assertEqual Nothing (compiledProfileRequiredBundleVersion compiled)-  for_-    [ VersionDeclared (OkfVersion 0 1),-      VersionDeclared (OkfVersion 0 2),-      VersionUnparseable "banana",-      VersionUndeclared-    ]-    (\declaration -> assertEqual [] (validateProfileVersion declaration compiled))---- | A minimal v0.2 profile whose only interesting member is the requirement under--- test.-requireBundleVersionProfile :: Maybe Text -> ProfileSpec-requireBundleVersionProfile required =-  (versionProfileWith "0.2" "optional" []) {requireBundleVersion = required}---- | A key the declared version supersedes is an error where it is /demanded/ and--- legal where it is merely documented. The optional list is how a team migrating--- a corpus says "tolerated but not demanded", and making it an error everywhere--- would leave no way to describe a migration.-testProfileVersionSupersededField :: Either Text ()-testProfileVersionSupersededField = do-  let timestampRule = fieldRule "timestamp" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing Nothing-      superseded = FieldSupersededInOkfVersion Nothing (fieldPath "timestamp") "0.2" "0.2"-  assertEqual-    (Left (superseded :| []))-    (compileProfile (versionProfileWith "0.2" "required" [timestampRule]))-  assertEqual-    (Left (superseded :| []))-    (compileProfile (versionProfileWith "0.2" "recommended" [timestampRule]))-  -- The migration shape, and the v0.1 profile that has no reason to be told-  -- anything at all.-  for_ [versionProfileWith "0.2" "optional" [timestampRule], versionProfileWith "0.1" "required" [timestampRule]] $ \spec ->-    case compileProfile spec of-      Left errs -> Left ("expected a clean compile, got " <> Text.pack (show (toList errs)))-      Right _ -> Right ()---- | The actor formats encode the specification §7 convention v0.2 introduced, so--- naming one under a v0.1 declaration is incoherent. A format is an okf--- descriptor feature rather than a key name, which is exactly why this check is--- safe where the mirror check on key names is not — see--- 'testProfileVersionDoesNotJudgeKeyNames'.-testProfileVersionActorFormat :: Either Text ()-testProfileVersionActorFormat = do-  let actorRule = fieldRule "author" Nothing [] Any (Just Actor) Nothing Nothing Nothing-      humanRule = fieldRule "author" Nothing [] Any (Just Profile.HumanActor) Nothing Nothing Nothing-  assertEqual-    (Left (FormatRequiresOkfVersion Nothing (fieldPath "author") Actor "0.1" "0.2" :| []))-    (compileProfile (versionProfileWith "0.1" "optional" [actorRule]))-  assertEqual-    (Left (FormatRequiresOkfVersion Nothing (fieldPath "author") Profile.HumanActor "0.1" "0.2" :| []))-    (compileProfile (versionProfileWith "0.1" "optional" [humanRule]))-  -- The same rule under a v0.2 declaration is exactly what the format is for.-  case compileProfile (versionProfileWith "0.2" "optional" [actorRule]) of-    Left errs -> Left ("expected a v0.2 actor rule to compile, got " <> Text.pack (show (toList errs)))-    Right _ -> Right ()---- | The check okf deliberately does /not/ perform, asserted so it is not added--- back by someone who thinks it was forgotten.------ A v0.1 profile constraining its own @status@, @sources@, or @verified@ key is--- coherent: per @docs\/adr\/1-profile-declared-document-ids.md@ constraining keys--- the core format does not own is what profiles are /for/, and these are ordinary--- words teams were already using before v0.2 claimed them. Rejecting--- @field.enum "status" ["proposed", "accepted"]@ for naming an ADR lifecycle--- would be a false positive on a descriptor okf cannot see.-testProfileVersionDoesNotJudgeKeyNames :: Either Text ()-testProfileVersionDoesNotJudgeKeyNames =-  for_ ["status", "sources", "verified", "generated", "stale_after", "usage_window"] $ \key ->-    let houseRule = fieldRule key Nothing ["proposed", "accepted"] Any Nothing Nothing Nothing Nothing-     in case compileProfile (versionProfileWith "0.1" "optional" [houseRule]) of-          Left errs ->-            Left ("a v0.1 profile naming " <> key <> " should compile, got " <> Text.pack (show (toList errs)))-          Right _ -> Right ()--lookupBaseRule :: CompiledProfile -> Text -> Either Text EffectiveFieldRule-lookupBaseRule compiled key =-  maybe-    (Left ("expected a compiled rule for " <> key))-    Right-    (Map.lookup key (compiledProfileBaseRules compiled))--reviewScopes :: [Text]-reviewScopes = ["content", "technical-accuracy", "editorial", "catalog-metadata", "content-and-metadata"]--testConditionDefinitionErrors :: Either Text ()-testConditionDefinitionErrors = do-  let source key values sourceCardinality =-        fieldRule key Nothing values sourceCardinality Nothing Nothing Nothing Nothing-      target key sourceKey values =-        fieldRule key Nothing [] Any Nothing Nothing Nothing (Just (FieldCondition sourceKey values))-      compileWith rules =-        compileProfile-          typeAwareProfileSpec-            { frontmatter = FrontmatterRules {required = rules, recommended = [], optional = []},-              allowUnknownTypes = True,-              types = []-            }-      targetPath key = fieldPath key-  assertEqual-    (Left (EmptyConditionValues Nothing (targetPath "target") (targetPath "status") :| []))-    (compileWith [source "status" ["active"] Scalar, target "target" "status" []])-  assertEqual-    (Left (ConditionFieldNotDeclared Nothing (targetPath "target") (targetPath "missing") :| []))-    (compileWith [target "target" "missing" ["active"]])-  assertEqual-    (Left (ConditionFieldNotScalar Nothing (targetPath "target") (targetPath "status") List :| []))-    (compileWith [source "status" ["active"] List, target "target" "status" ["active"]])-  assertEqual-    (Left (ConditionFieldOpenVocabulary Nothing (targetPath "target") (targetPath "status") :| []))-    (compileWith [source "status" [] Scalar, target "target" "status" ["active"]])-  assertEqual-    (Left (ConditionFieldHasUnreachableValues Nothing (targetPath "target") (targetPath "status") ["superseded"] ["active"] :| []))-    (compileWith [source "status" ["active"] Scalar, target "target" "status" ["superseded"]])-  assertEqual-    (Left (SelfConditionalField Nothing (targetPath "status") :| []))-    (compileWith [fieldRule "status" Nothing ["active"] Scalar Nothing Nothing Nothing (Just (FieldCondition "status" ["active"]))])-  let nestedCrossScope =-        NestedRules-          { required =-              [ nestedFieldRule "kind" Nothing ["human", "model"] Scalar Nothing Nothing Nothing,-                nestedFieldRule "provider" Nothing [] Scalar Nothing Nothing (Just (FieldCondition "status" ["active"]))-              ],-            recommended = [],-            optional = []-          }-      crossScopeProfile =-        typeAwareProfileSpec-          { frontmatter =-              FrontmatterRules-                { required =-                    [ source "status" ["active"] Scalar,-                      fieldRule "reviews" Nothing [] List Nothing (Just nestedCrossScope) Nothing Nothing-                    ],-                  recommended = [],-                  optional = []-                },-            allowUnknownTypes = True,-            types = []-          }-  assertEqual-    (Left (ConditionFieldNotDeclared Nothing (nestedDefinitionTestPath "reviews" "provider") (nestedDefinitionTestPath "reviews" "status") :| []))-    (compileProfile crossScopeProfile)-  where-    nestedDefinitionTestPath parent child =-      FieldPath (FieldName parent :| [FieldName child])--testTopLevelConditionalPresence :: Either Text ()-testTopLevelConditionalPresence = do-  let statusRule = fieldRule "status" Nothing ["active", "superseded"] Scalar Nothing Nothing Nothing Nothing-      recommendedTarget =-        fieldRule "supersededBy" Nothing ["ADR-1"] Scalar Nothing Nothing Nothing (Just (FieldCondition "status" ["active"]))-      requiredTarget =-        fieldRule "supersededBy" Nothing ["ADR-1"] Scalar Nothing Nothing Nothing (Just (FieldCondition "status" ["superseded"]))-      base =-        typeAwareProfileSpec-          { frontmatter = FrontmatterRules {required = [requiredField "type", statusRule], recommended = [recommendedTarget], optional = []},-            allowUnknownTypes = True,-            types =-              [ withTypeFrontmatter-                  FrontmatterRules {required = [requiredTarget], recommended = [], optional = []}-                  (firstTypeRule typeAwareProfileSpec)-              ]-          }-  compiled <- firstShow (compileProfile base)-  active <- profileConcept "active" [("type", String "Owned Concept"), ("status", String "active")] "# Active\n"-  superseded <- profileConcept "superseded" [("type", String "Owned Concept"), ("status", String "superseded")] "# Superseded\n"-  invalidPresent <- profileConcept "invalid-present" [("type", String "Owned Concept"), ("status", String "active"), ("supersededBy", String "ADR-2")] "# Invalid\n"-  missingSource <- profileConcept "missing-source" [("type", String "Owned Concept")] "# Missing source\n"-  invalidSource <- profileConcept "invalid-source" [("type", String "Owned Concept"), ("status", String "unknown")] "# Invalid source\n"-  wrongShapeSource <- profileConcept "wrong-shape-source" [("type", String "Owned Concept"), ("status", toJSON (["active"] :: [Text]))] "# Wrong shape\n"-  activeId <- parseTestConceptId "active"-  supersededId <- parseTestConceptId "superseded"-  invalidId <- parseTestConceptId "invalid-present"-  missingSourceId <- parseTestConceptId "missing-source"-  invalidSourceId <- parseTestConceptId "invalid-source"-  wrongShapeSourceId <- parseTestConceptId "wrong-shape-source"-  assertEqual [] (validateProfile PermissiveConformance compiled [active])-  assertEqual-    [MissingRecommendedProfileField activeId "supersededBy" (Just (FieldCondition "status" ["active"]))]-    (validateProfile StrictAuthoring compiled [active])-  assertEqual-    [MissingProfileField supersededId "supersededBy" (Just (FieldCondition "status" ["superseded"]))]-    (validateProfile PermissiveConformance compiled [superseded])-  assertEqual-    [ValueNotInVocabulary invalidId (fieldPath "supersededBy") ["ADR-1"] (String "ADR-2")]-    (validateProfile PermissiveConformance compiled [invalidPresent])-  assertEqual-    [MissingProfileField missingSourceId "status" Nothing]-    (validateProfile PermissiveConformance compiled [missingSource])-  assertEqual-    [ValueNotInVocabulary invalidSourceId (fieldPath "status") ["active", "superseded"] (String "unknown")]-    (validateProfile PermissiveConformance compiled [invalidSource])-  assertEqual-    [CardinalityMismatch wrongShapeSourceId (fieldPath "status") Scalar (toJSON (["active"] :: [Text]))]-    (validateProfile PermissiveConformance compiled [wrongShapeSource])--testNestedConditionalPresence :: Either Text ()-testNestedConditionalPresence = do-  let nestedRules =-        NestedRules-          { required =-              [ nestedFieldRule "kind" Nothing ["human", "model"] Scalar Nothing Nothing Nothing,-                nestedFieldRule "provider" Nothing [] Scalar Nothing Nothing (Just (FieldCondition "kind" ["model"]))-              ],-            recommended =-              [nestedFieldRule "notes" Nothing [] Scalar Nothing Nothing (Just (FieldCondition "kind" ["human"]))],-            optional = []-          }-      spec = nestedProfileWithRules List nestedRules Nothing-  compiled <- firstShow (compileProfile spec)-  concept <--    profileConcept-      "conditional-reviews"-      [ ("type", String "Reviewed Concept"),-        ("reviews", toJSON [object ["kind" .= ("model" :: Text)], object ["kind" .= ("human" :: Text)], object []])-      ]-      "# Conditional reviews\n"-  cid <- parseTestConceptId "conditional-reviews"-  assertEqual-    [MissingNestedProfileField cid (nestedTestPath 0 "provider") (Just (FieldCondition "kind" ["model"])), MissingNestedProfileField cid (nestedTestPath 2 "kind") Nothing]-    (validateProfile PermissiveConformance compiled [concept])-  assertEqual-    [ MissingNestedProfileField cid (nestedTestPath 0 "provider") (Just (FieldCondition "kind" ["model"])),-      MissingRecommendedNestedProfileField cid (nestedTestPath 1 "notes") (Just (FieldCondition "kind" ["human"])),-      MissingNestedProfileField cid (nestedTestPath 2 "kind") Nothing-    ]-    (validateProfile StrictAuthoring compiled [concept])--testReferenceDefinitionErrors :: Either Text ()-testReferenceDefinitionErrors = do-  let referenceRule key prefix schemes fieldFormat =-        fieldRule-          key-          Nothing-          []-          Scalar-          fieldFormat-          Nothing-          (Just (handleReferenceRule prefix schemes False))-          Nothing-      baseType = firstTypeRule testDocumentIdProfileSpec-      specWith profileIdField typeRules profileRules =-        testDocumentIdProfileSpec-          { frontmatter = FrontmatterRules {required = profileRules, recommended = [], optional = []},-            idField = profileIdField,-            requireBundleVersion = Nothing,-            types = typeRules-          }-      path = fieldPath "supersedes"-      invalidPrefixType = baseType {idPrefix = Just "1ADR"}-      invalidPrefixSpec = specWith (Just "docId") [invalidPrefixType] [referenceRule "supersedes" "1ADR" [] Nothing]-      undeclaredPrefixSpec = specWith (Just "docId") [baseType] [referenceRule "supersedes" "PAT" [] Nothing]-      missingIdFieldSpec = specWith Nothing [baseType] [referenceRule "supersedes" "ADR" [] Nothing]-      invalidSchemeSpec = specWith (Just "docId") [baseType] [referenceRule "supersedes" "ADR" ["mori_", "MORI_"] Nothing]-      formatSpec = specWith (Just "docId") [baseType] [referenceRule "supersedes" "ADR" [] (Just (DocumentHandle "ADR"))]-      typeReference = referenceRule "supersedes" "RFC" [] Nothing-      conflictingType :: TypeRule-      conflictingType = baseType & #frontmatter .~ FrontmatterRules {required = [typeReference], recommended = [], optional = []}-      rfcType = baseType {type_ = "RFC", idPrefix = Just "RFC", pathPattern = Nothing}-      conflictSpec = specWith (Just "docId") [conflictingType, rfcType] [referenceRule "supersedes" "ADR" [] Nothing]-  assertEqual-    (Left (InvalidReferencePrefix Nothing path "1ADR" :| []))-    (compileProfile invalidPrefixSpec)-  assertEqual-    (Left (ReferencePrefixNotDeclared Nothing path "PAT" :| []))-    (compileProfile undeclaredPrefixSpec)-  assertEqual-    (Left (ReferenceRequiresIdField Nothing path :| []))-    (compileProfile missingIdFieldSpec)-  assertEqual-    (Left (InvalidExternalReferenceScheme Nothing path "mori_" :| []))-    (compileProfile invalidSchemeSpec)-  assertEqual-    (Left (ReferenceWithFormat Nothing path (DocumentHandle "ADR") :| []))-    (compileProfile formatSpec)-  assertEqual-    (Left (ConflictingReferencePrefix "Decision Record" path "ADR" "RFC" :| []))-    (compileProfile conflictSpec)--testCompileNestedReferenceAndUniqueness :: IO (Either Text ())-testCompileNestedReferenceAndUniqueness = do-  loaded <- loadNestedReferenceSpec-  pure $ do-    spec <- loaded-    compiled <- firstShow (compileProfile spec)-    dependencies <- lookupBaseRule compiled "dependencies"-    acceptanceCriteria <- lookupBaseRule compiled "acceptanceCriteria"-    assertEqual (Just "id") (fieldRuleUniqueBy acceptanceCriteria)-    case fieldRuleElementFields dependencies >>= Map.lookup "ref" of-      Nothing -> Left "expected a compiled dependencies.ref rule"-      Just referenceRule ->-        assertEqual-          ( Just-              ( HandleReferenceRule-                  "IR"-                  ["mori"]-                  False-                  False-                  (Just nestedReferencePattern)-              )-          )-          (fieldRuleReference referenceRule)--testNestedReferenceAndUniquenessValidation :: IO (Either Text ())-testNestedReferenceAndUniquenessValidation = do-  loaded <- loadNestedReferenceSpec-  validRoot <- fixturePath "profile-nested-references-and-uniqueness-valid"-  invalidRoot <- fixturePath "profile-nested-references-and-uniqueness-invalid"-  validConcepts <- readBundle validRoot-  invalidConcepts <- readBundle invalidRoot-  pure $ do-    spec <- loaded-    compiled <- firstShow (compileProfile spec)-    assertEqual [] (validateProfile PermissiveConformance compiled validConcepts)-    duplicateId <- parseTestConceptId "requests/duplicate"-    assertEqual-      [DuplicateNestedFieldValue duplicateId (objectMemberPath "acceptanceCriteria" "id") (String "AC-1") (0 :| [1])]-      (validateProfile PermissiveConformance compiled invalidConcepts)-    assertReferenceCase compiled "local" "IR-1" (LocalDocumentReferenceNotAllowed <$> pureCaseId "local" <*> pure (nestedTestPathFor "dependencies" 0 "ref") <*> pure "IR-1")-    assertReferenceCase compiled "scheme" "https://example.test/IR-1" (ExternalReferenceSchemeNotAllowed <$> pureCaseId "scheme" <*> pure (nestedTestPathFor "dependencies" 0 "ref") <*> pure "https" <*> pure ["mori"])-    assertPatternCase compiled "artifact-kind" "mori://namespace/project/okf/decisions/concepts/IR-1"-    assertPatternCase compiled "leading-zero" "mori://namespace/project/okf/improvement-requests/concepts/IR-01"-    assertPatternCase compiled "query" "mori://namespace/project/okf/improvement-requests/concepts/IR-1?x=1"-    assertPatternCase compiled "fragment" "mori://namespace/project/okf/improvement-requests/concepts/IR-1#x"-    malformed <- referenceConcept "malformed" "not a reference" ["AC-1", "AC-2"]-    malformedId <- parseTestConceptId "requests/malformed"-    assertEqual-      [MalformedDocumentReference malformedId (nestedTestPathFor "dependencies" 0 "ref") (String "not a reference")]-      (validateProfile PermissiveConformance compiled [malformed])-    grouped <- referenceConcept "groups" canonicalNestedReference ["AC-1", "AC-2", "AC-1", "AC-2"]-    groupedId <- parseTestConceptId "requests/groups"-    assertEqual-      [ DuplicateNestedFieldValue groupedId (objectMemberPath "acceptanceCriteria" "id") (String "AC-1") (0 :| [2]),-        DuplicateNestedFieldValue groupedId (objectMemberPath "acceptanceCriteria" "id") (String "AC-2") (1 :| [3])-      ]-      (validateProfile PermissiveConformance compiled [grouped])-  where-    pureCaseId name = parseTestConceptId ("requests/" <> name)--    assertReferenceCase compiled name raw expectedAction = do-      concept <- referenceConcept name raw ["AC-1", "AC-2"]-      expected <- expectedAction-      assertEqual [expected] (validateProfile PermissiveConformance compiled [concept])--    assertPatternCase compiled name raw = do-      cid <- parseTestConceptId ("requests/" <> name)-      assertReferenceCase-        compiled-        name-        raw-        (Right (ExternalReferencePatternMismatch cid (nestedTestPathFor "dependencies" 0 "ref") raw nestedReferencePattern))--testNestedReferenceAndUniquenessDefinitionErrors :: IO (Either Text ())-testNestedReferenceAndUniquenessDefinitionErrors = do-  loaded <- loadNestedReferenceSpec-  pure $ do-    spec <- loaded-    dependencies <- lookupRaw "dependencies" spec-    acceptance <- lookupRaw "acceptanceCriteria" spec-    let invalidPattern = updateNestedRule "ref" (\rule -> rule {reference = setPattern "[" <$> rule ^. #reference}) dependencies-        invalidPatternSpec = replaceBaseRule invalidPattern spec-    assertSingleDefinitionError-      (\case InvalidExternalUriPattern Nothing path "[" _ -> path == objectMemberPath "dependencies" "ref"; _ -> False)-      (compileProfile invalidPatternSpec)--    let typePattern = updateNestedRule "ref" (\rule -> rule {reference = setPattern "mori://different" <$> rule ^. #reference}) dependencies-        patternConflictSpec = addTypeRule typePattern spec-    assertSingleDefinitionError-      (== ConflictingExternalUriPatterns "Improvement Request" (objectMemberPath "dependencies" "ref") nestedReferencePattern "mori://different")-      (compileProfile patternConflictSpec)--    let noElements = (requiredField "plainRecords") {uniqueBy = Just "id"}-    assertSingleDefinitionError-      (== UniqueByRequiresElementFields Nothing (fieldPath "plainRecords") "id")-      (compileProfile (replaceBaseRule noElements spec))--    let missingMember = acceptance {uniqueBy = Just "missing"}-    assertSingleDefinitionError-      (== UniqueByFieldNotDeclared Nothing (objectMemberPath "acceptanceCriteria" "missing"))-      (compileProfile (replaceBaseRule missingMember spec))--    let optionalMember = updateNestedPresence "id" acceptance-    assertSingleDefinitionError-      (== UniqueByFieldNotUnconditionallyRequired Nothing (objectMemberPath "acceptanceCriteria" "id"))-      (compileProfile (replaceBaseRule optionalMember spec))--    let listMember = updateNestedRule "id" (\rule -> rule {cardinality = List}) acceptance-    assertSingleDefinitionError-      (== UniqueByFieldNotScalar Nothing (objectMemberPath "acceptanceCriteria" "id") List)-      (compileProfile (replaceBaseRule listMember spec))--    let conflictingUnique = acceptance {uniqueBy = Just "text"}-    assertSingleDefinitionError-      (== ConflictingUniqueBy "Improvement Request" (fieldPath "acceptanceCriteria") "id" "text")-      (compileProfile (addTypeRule conflictingUnique spec))-  where-    setPattern :: Text -> HandleReferenceRule -> HandleReferenceRule-    setPattern patternText policy = policy {externalUriPattern = Just patternText}--    lookupRaw :: Text -> ProfileSpec -> Either Text FieldRule-    lookupRaw key spec =-      case [rule | rule <- spec ^. #frontmatter . #required, rule ^. #field == key] of-        [rule] -> Right rule-        _ -> Left ("expected one raw rule for " <> key)--    replaceBaseRule :: FieldRule -> ProfileSpec -> ProfileSpec-    replaceBaseRule replacement spec =-      spec-        { frontmatter =-            (spec ^. #frontmatter)-              { required = replacement : filter ((/= replacement ^. #field) . (^. #field)) (spec ^. #frontmatter . #required)-              }-        }--    addTypeRule :: FieldRule -> ProfileSpec -> ProfileSpec-    addTypeRule typeField spec =-      spec-        { types =-            [ typeRule-                { frontmatter = FrontmatterRules {required = [typeField], recommended = [], optional = []}-                }-            | typeRule <- spec ^. #types-            ]-        }--    updateNestedRule :: Text -> (NestedFieldRule -> NestedFieldRule) -> FieldRule -> FieldRule-    updateNestedRule key change parent =-      parent {elementFields = updateRules <$> parent ^. #elementFields}-      where-        updateRules :: NestedRules -> NestedRules-        updateRules rules =-          rules-            { required = map update (rules ^. #required),-              recommended = map update (rules ^. #recommended),-              optional = map update (rules ^. #optional)-            }-        update rule | rule ^. #field == key = change rule-        update rule = rule--    updateNestedPresence :: Text -> FieldRule -> FieldRule-    updateNestedPresence key parent =-      parent {elementFields = move <$> parent ^. #elementFields}-      where-        move :: NestedRules -> NestedRules-        move rules =-          let (selected, remaining) = List.partition ((== key) . (^. #field)) (rules ^. #required)-           in rules {required = remaining, optional = selected <> rules ^. #optional}--    assertSingleDefinitionError matches = \case-      Left (definitionError :| []) | matches definitionError -> Right ()-      Left errors -> Left ("unexpected definition errors: " <> Text.pack (show (toList errors)))-      Right _ -> Left "expected profile definition to fail"--loadNestedReferenceSpec :: IO (Either Text ProfileSpec)-loadNestedReferenceSpec = do-  descriptorPath <- fixtureFilePath "profiles/nested-references-and-uniqueness.dhall"-  first ("failed to load nested reference profile: " <>) <$> loadProfileFile descriptorPath--nestedReferencePattern :: Text-nestedReferencePattern = "mori://[^/]+/[^/]+/okf/improvement-requests/concepts/IR-[1-9][0-9]*"--canonicalNestedReference :: Text-canonicalNestedReference = "mori://namespace/project/okf/improvement-requests/concepts/IR-9"--referenceConcept :: Text -> Text -> [Text] -> Either Text Concept-referenceConcept name rawReference criterionIds =-  profileConcept-    ("requests/" <> name)-    [ ("type", String "Improvement Request"),-      ("requestId", String "IR-1"),-      ("dependencies", toJSON [object ["ref" .= rawReference]]),-      ( "acceptanceCriteria",-        toJSON-          [ object ["id" .= criterionId, "text" .= ("Criterion " <> criterionId)]-          | criterionId <- criterionIds-          ]-      )-    ]-    "# Request\n"--nestedTestPathFor :: Text -> Int -> Text -> FieldPath-nestedTestPathFor parent elementIndex child =-  FieldPath (FieldName parent :| [ArrayIndex elementIndex, FieldName child])--testDocumentReferenceValidation :: Either Text ()-testDocumentReferenceValidation = do-  let referencePolicy = handleReferenceRule "ADR" ["mori", "MORI"] False-      selfPolicy = handleReferenceRule "ADR" [] True-      referenceRules =-        [ fieldRule "references" Nothing [] List Nothing Nothing (Just referencePolicy) Nothing,-          fieldRule "selfReference" Nothing [] Scalar Nothing Nothing (Just selfPolicy) Nothing-        ]-      spec :: ProfileSpec-      spec =-        testDocumentIdProfileSpec-          & #frontmatter-          .~ FrontmatterRules-            { required = [requiredField "type", requiredField "title"],-              recommended = referenceRules,-              optional = []-            }-  compiled <- firstShow (compileProfile spec)-  duplicateA <- decisionConcept "decisions/duplicate-a" "Duplicate A" "ADR-3" []-  duplicateB <- decisionConcept "decisions/duplicate-b" "Duplicate B" "ADR-3" []-  source <--    decisionConcept-      "decisions/source"-      "Source"-      "ADR-1"-      [ ( "references",-          toJSON-            [ String "ADR-2",-              String "ADR-99",-              String "PAT-3",-              String "not a reference",-              String "https://example.test/external",-              String "MORI://shinzui/okf/docs/one",-              String "ADR-1",-              Number 7,-              String "ADR-3"-            ]-        ),-        ("selfReference", String "ADR-1")-      ]-  target <- decisionConcept "decisions/target" "Target" "ADR-2" []-  duplicateAId <- parseTestConceptId "decisions/duplicate-a"-  duplicateBId <- parseTestConceptId "decisions/duplicate-b"-  sourceId <- parseTestConceptId "decisions/source"-  assertEqual-    [ DanglingHandleReference sourceId (indexedPath "references" 1) "ADR-99",-      ReferenceHandlePrefixMismatch sourceId (indexedPath "references" 2) "PAT-3" "ADR",-      MalformedDocumentReference sourceId (indexedPath "references" 3) (String "not a reference"),-      ExternalReferenceSchemeNotAllowed sourceId (indexedPath "references" 4) "https" ["mori"],-      SelfDocumentReference sourceId (indexedPath "references" 6) "ADR-1",-      MalformedDocumentReference sourceId (indexedPath "references" 7) (Number 7),-      DuplicateDocumentId "ADR-3" duplicateAId duplicateBId-    ]-    (validateProfile PermissiveConformance compiled [target, source, duplicateB, duplicateA])-  where-    decisionConcept cid title documentId extraFields =-      profileConcept-        cid-        ([("type", String "Decision Record"), ("title", String title), ("docId", String documentId)] <> extraFields)-        ("# " <> title <> "\n")-    indexedPath key elementIndex = FieldPath (FieldName key :| [ArrayIndex elementIndex])---- | The whole point of the third presence list: absence is silent in both--- validation modes, while a present value is checked exactly as hard as it would--- be under @required@.-testOptionalFieldPresence :: Either Text ()-testOptionalFieldPresence = do-  let optionalRules =-        [ fieldRule "supersedes" Nothing ["ADR-1", "ADR-2"] Scalar Nothing Nothing Nothing Nothing,-          fieldRule "reviewedAt" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing Nothing,-          fieldRule "tags" Nothing [] List Nothing Nothing Nothing Nothing-        ]-      spec =-        typeAwareProfileSpec-          { frontmatter =-              FrontmatterRules-                { required = [requiredField "type"],-                  recommended = [requiredField "owner"],-                  optional = optionalRules-                },-            allowUnknownTypes = True,-            types = []-          }-  compiled <- firstShow (compileProfile spec)-  absent <- profileConcept "optional/absent" [("type", String "Extension"), ("owner", String "Ari")] "# Absent\n"-  -- A correctly shaped empty value counts as absent, so it is as silent as a key-  -- that was never written. (A blank value on a field that also declares a-  -- vocabulary or format still fails that check; presence and value are-  -- independent, which is exactly what this feature relies on.)-  emptied <--    profileConcept-      "optional/emptied"-      [ ("type", String "Extension"),-        ("owner", String "Ari"),-        ("tags", toJSON ([] :: [Text]))-      ]-      "# Emptied\n"-  valid <--    profileConcept-      "optional/valid"-      [ ("type", String "Extension"),-        ("owner", String "Ari"),-        ("supersedes", String "ADR-1"),-        ("reviewedAt", String "2026-07-30T00:00:00Z"),-        ("tags", toJSON (["profiles"] :: [Text]))-      ]-      "# Valid\n"-  invalid <--    profileConcept-      "optional/invalid"-      [ ("type", String "Extension"),-        ("owner", String "Ari"),-        ("supersedes", String "ADR-9"),-        ("reviewedAt", String "2026-13-45T99:99:99Z"),-        ("tags", String "profiles")-      ]-      "# Invalid\n"-  invalidId <- parseTestConceptId "optional/invalid"-  for_ [PermissiveConformance, StrictAuthoring] $ \validationProfile -> do-    assertEqual [] (validateProfile validationProfile compiled [absent])-    assertEqual [] (validateProfile validationProfile compiled [emptied])-    assertEqual [] (validateProfile validationProfile compiled [valid])-    assertEqual-      [ ValueFormatMismatch invalidId (fieldPath "reviewedAt") Rfc3339Utc (String "2026-13-45T99:99:99Z"),-        ValueNotInVocabulary invalidId (fieldPath "supersedes") ["ADR-1", "ADR-2"] (String "ADR-9"),-        CardinalityMismatch invalidId (fieldPath "tags") List (String "profiles")-      ]-      (validateProfile validationProfile compiled [invalid])---- | An optional field carrying a document-reference policy resolves handles the--- same way a required one does; only the absence check differs.-testOptionalReferenceValidation :: Either Text ()-testOptionalReferenceValidation = do-  let spec :: ProfileSpec-      spec =-        testDocumentIdProfileSpec-          & #frontmatter-          .~ FrontmatterRules-            { required = [requiredField "type", requiredField "title"],-              recommended = [],-              optional = [fieldRule "supersedes" Nothing [] Scalar Nothing Nothing (Just (handleReferenceRule "ADR" [] False)) Nothing]-            }-  compiled <- firstShow (compileProfile spec)-  target <- decisionTestConcept "decisions/target" "Target" "ADR-1" []-  silent <- decisionTestConcept "decisions/silent" "Silent" "ADR-2" []-  dangling <- decisionTestConcept "decisions/dangling" "Dangling" "ADR-3" [("supersedes", String "ADR-99")]-  danglingId <- parseTestConceptId "decisions/dangling"-  for_ [PermissiveConformance, StrictAuthoring] $ \validationProfile -> do-    assertEqual [] (validateProfile validationProfile compiled [target, silent])-    assertEqual-      [DanglingHandleReference danglingId (fieldPath "supersedes") "ADR-99"]-      (validateProfile validationProfile compiled [target, dangling])---- | Optional members of a list-element record behave the same way inside every--- record: never missing, always checked when present.-testOptionalNestedFieldPresence :: Either Text ()-testOptionalNestedFieldPresence = do-  let nestedRules =-        NestedRules-          { required = [nestedFieldRule "kind" Nothing ["human", "model"] Scalar Nothing Nothing Nothing],-            recommended = [nestedFieldRule "notes" Nothing [] Scalar Nothing Nothing Nothing],-            optional = [nestedFieldRule "model" Nothing ["opus", "sonnet"] Scalar Nothing Nothing Nothing]-          }-  compiled <- firstShow (compileProfile (nestedProfileWithRules Any nestedRules Nothing))-  concept <--    profileConcept-      "reviewed/optional"-      [ ("type", String "Reviewed Concept"),-        ( "reviews",-          toJSON-            [ object ["kind" .= ("human" :: Text), "notes" .= ("looks good" :: Text)],-              object ["kind" .= ("model" :: Text), "notes" .= ("ran it" :: Text), "model" .= ("opus" :: Text)],-              object ["kind" .= ("model" :: Text), "notes" .= ("ran it" :: Text), "model" .= ("gpt" :: Text)]-            ]-        )-      ]-      "# Optional\n"-  cid <- parseTestConceptId "reviewed/optional"-  for_ [PermissiveConformance, StrictAuthoring] $ \validationProfile ->-    assertEqual-      [ValueNotInVocabulary cid (nestedTestPath 2 "model") ["opus", "sonnet"] (String "gpt")]-      (validateProfile validationProfile compiled [concept])---- | An optional key is declared for the purposes of field-name closure, so a--- closed profile accepts it and still catches a misspelling of it.-testOptionalFieldClosure :: Either Text ()-testOptionalFieldClosure = do-  let closed =-        typeAwareProfileSpec-          { frontmatter =-              FrontmatterRules-                { required = [requiredField "type"],-                  recommended = [],-                  optional = [requiredField "supersedes"]-                },-            allowUnknownTypes = True,-            allowUnknownFields = False,-            types = []-          }-  compiled <- firstShow (compileProfile closed)-  declared <- profileConcept "closed/declared" [("type", String "Extension"), ("supersedes", String "ADR-1")] "# Declared\n"-  typo <- profileConcept "closed/typo" [("type", String "Extension"), ("supersedse", String "ADR-1")] "# Typo\n"-  typoId <- parseTestConceptId "closed/typo"-  assertEqual [] (validateProfile PermissiveConformance compiled [declared])-  assertEqual-    [FieldNotInProfile typoId "supersedse"]-    (validateProfile PermissiveConformance compiled [typo])---- | Declaring a key optional at one scope does not cancel the other scope's--- presence clause. Merging accumulates clauses precisely so a type rule can--- narrow but never silently weaken a profile-wide expectation.-testOptionalDoesNotCancelOtherScope :: Either Text ()-testOptionalDoesNotCancelOtherScope = do-  let ownerRule = requiredField "owner"-      specWith profileRules typeRules =-        typeAwareProfileSpec-          { frontmatter = profileRules,-            allowUnknownTypes = True,-            types = [withTypeFrontmatter typeRules (firstTypeRule typeAwareProfileSpec)]-          }-      recommendedThenOptional =-        specWith-          FrontmatterRules {required = [requiredField "type"], recommended = [ownerRule], optional = []}-          FrontmatterRules {required = [], recommended = [], optional = [ownerRule]}-      optionalThenRecommended =-        specWith-          FrontmatterRules {required = [requiredField "type"], recommended = [], optional = [ownerRule]}-          FrontmatterRules {required = [], recommended = [ownerRule], optional = []}-  concept <- profileConcept "owned/one" [("type", String "Owned Concept")] "# One\n"-  cid <- parseTestConceptId "owned/one"-  for_ [recommendedThenOptional, optionalThenRecommended] $ \spec -> do-    compiled <- firstShow (compileProfile spec)-    assertEqual [] (validateProfile PermissiveConformance compiled [concept])-    assertEqual-      [MissingRecommendedProfileField cid "owner" Nothing]-      (validateProfile StrictAuthoring compiled [concept])---- | Compilation rejects the two contradictions the third list makes possible: a--- key classified twice at one scope, and a condition on a rule that has no--- presence check for it to gate.-testOptionalDefinitionErrors :: Either Text ()-testOptionalDefinitionErrors = do-  let key name = requiredField name-      specWith rules =-        typeAwareProfileSpec {frontmatter = rules, allowUnknownTypes = True, types = []}-      conditioned name sourceKey =-        fieldRule name Nothing [] Any Nothing Nothing Nothing (Just (FieldCondition sourceKey ["active"]))-      statusRule = fieldRule "status" Nothing ["active"] Scalar Nothing Nothing Nothing Nothing-  assertEqual-    (Left (ConflictingFieldRequirement Nothing "owner" :| []))-    (compileProfile (specWith FrontmatterRules {required = [key "type", key "owner"], recommended = [], optional = [key "owner"]}))-  assertEqual-    (Left (ConflictingFieldRequirement Nothing "owner" :| []))-    (compileProfile (specWith FrontmatterRules {required = [key "type"], recommended = [key "owner"], optional = [key "owner"]}))-  assertEqual-    (Left (DuplicateFieldRule Nothing "optional" "owner" :| []))-    (compileProfile (specWith FrontmatterRules {required = [key "type"], recommended = [], optional = [key "owner", key "owner"]}))-  assertEqual-    (Left (OptionalFieldWithCondition Nothing (fieldPath "supersededBy") :| []))-    ( compileProfile-        (specWith FrontmatterRules {required = [key "type", statusRule], recommended = [], optional = [conditioned "supersededBy" "status"]})-    )-  let nestedRules =-        NestedRules-          { required = [nestedFieldRule "kind" Nothing ["model"] Scalar Nothing Nothing Nothing],-            recommended = [],-            optional = [nestedFieldRule "model" Nothing [] Scalar Nothing Nothing (Just (FieldCondition "kind" ["model"]))]-          }-  assertEqual-    (Left (OptionalFieldWithCondition Nothing (FieldPath (FieldName "reviews" :| [FieldName "model"])) :| []))-    (compileProfile (nestedProfileWithRules Any nestedRules Nothing))-  let optionalParent =-        specWith-          FrontmatterRules-            { required = [key "type"],-              recommended = [],-              optional = [fieldRule "reviews" Nothing [] List Nothing (Just nestedRules) Nothing Nothing]-            }-  assertEqual-    (Left (OptionalFieldWithCondition Nothing (FieldPath (FieldName "reviews" :| [FieldName "model"])) :| []))-    (compileProfile optionalParent)--decisionTestConcept :: Text -> Text -> Text -> [(Text, Value)] -> Either Text Concept-decisionTestConcept cid title documentId extraFields =-  profileConcept-    cid-    ([("type", String "Decision Record"), ("title", String title), ("docId", String documentId)] <> extraFields)-    ("# " <> title <> "\n")---- | The end-to-end proof, run against the fixture bundle a reader can also run--- from the command line. Absence of the three optional keys is silent in both--- modes; the one genuine recommendation still fails under strict authoring; the--- conditional requirement in the same type still fires; and every optional key--- that /is/ present is checked as hard as a required one.-testOptionalFieldsFixture :: IO (Either Text ())-testOptionalFieldsFixture = do-  descriptorPath <- fixtureFilePath "profiles/optional-fields.dhall"-  conditionPath <- fixtureFilePath "profiles/optional-conditional-invalid.dhall"-  collisionPath <- fixtureFilePath "profiles/optional-collision-invalid.dhall"-  loaded <- loadProfileFile descriptorPath-  conditionLoaded <- loadProfileFile conditionPath-  collisionLoaded <- loadProfileFile collisionPath-  root <- fixturePath "profile-optional-fields"-  concepts <- readBundle root-  pure $ do-    spec <- first ("failed to load optional-fields profile: " <>) loaded-    compiled <- firstShow (compileProfile spec)-    conditionSpec <- first ("failed to load invalid optional-condition profile: " <>) conditionLoaded-    collisionSpec <- first ("failed to load invalid optional-collision profile: " <>) collisionLoaded-    assertEqual-      ( Left-          ( OptionalFieldWithCondition (Just "Decision Record") (FieldPath (FieldName "reviews" :| [FieldName "model"]))-              :| [OptionalFieldWithCondition (Just "Decision Record") (fieldPath "supersededBy")]-          )-      )-      (compileProfile conditionSpec)-    assertEqual-      ( Left-          ( ConflictingFieldRequirement Nothing "reviewedBy"-              :| [ConflictingFieldRequirement (Just "Decision Record") "owner"]-          )-      )-      (compileProfile collisionSpec)-    accepted <- parseTestConceptId "decisions/accepted"-    badSupersedes <- parseTestConceptId "decisions/bad-supersedes"-    superseded <- parseTestConceptId "decisions/superseded"-    let valueViolations =-          [ ValueFormatMismatch badSupersedes (fieldPath "decidedAt") Rfc3339Utc (String "not a timestamp"),-            ValueNotInVocabulary badSupersedes (nestedReviewPath 0 "model") ["opus", "sonnet"] (String "gpt"),-            DanglingHandleReference badSupersedes (fieldPath "supersedes") "ADR-99",-            MissingProfileField superseded "supersededBy" (Just (FieldCondition "status" ["superseded"]))-          ]-    assertEqual valueViolations (validateProfile PermissiveConformance compiled concepts)-    assertEqual-      (MissingRecommendedProfileField accepted "reviewedBy" Nothing : valueViolations)-      (validateProfile StrictAuthoring compiled concepts)-  where-    nestedReviewPath elementIndex key =-      FieldPath (FieldName "reviews" :| [ArrayIndex elementIndex, FieldName key])--testClosedFieldValidation :: Either Text ()-testClosedFieldValidation = do-  let ownedRule :: TypeRule-      ownedRule =-        withTypeFrontmatter-          FrontmatterRules {required = [requiredField "owner"], recommended = [], optional = []}-          (firstTypeRule typeAwareProfileSpec)-      reviewRule =-        withTypeName-          "Review"-          (withTypeFrontmatter FrontmatterRules {required = [requiredField "reviewer"], recommended = [], optional = []} ownedRule)-      closed =-        typeAwareProfileSpec-          { frontmatter = FrontmatterRules {required = [requiredField "type", requiredField "status"], recommended = [], optional = []},-            allowUnknownFields = False,-            idField = Just "requestId",-            requireBundleVersion = Nothing,-            types = [ownedRule, reviewRule]-          }-  compiled <- firstShow (compileProfile closed)-  typo <--    profileConcept-      "owned/typo"-      [ ("type", String "Owned Concept"),-        ("title", String "Typo"),-        ("description", String "Core"),-        ("timestamp", String "2026-07-29T00:00:00Z"),-        ("resource", String "https://example.test/typo"),-        ("tags", toJSON (["profiles"] :: [Text])),-        ("requestId", String "IR-1"),-        ("owner", String "Ari"),-        ("reviewer", String "Bo"),-        ("stauts", String "draft")-      ]-      "# Typo\n"-  cid <- parseTestConceptId "owned/typo"-  assertEqual-    [ MissingProfileField cid "status" Nothing,-      FieldNotInProfile cid "reviewer",-      FieldNotInProfile cid "stauts"-    ]-    (validateProfile PermissiveConformance compiled [typo])-  let reopened = closed {allowUnknownFields = True}-  reopenedCompiled <- firstShow (compileProfile reopened)-  assertEqual-    [MissingProfileField cid "status" Nothing]-    (validateProfile PermissiveConformance reopenedCompiled [typo])---- | The behavior this plan exists to deliver: a profile can require a--- mapping-valued key and can demand a member of that mapping, reported at a path--- such as @generated.by@.-testValidateObjectMember :: Either Text ()-testValidateObjectMember = do-  compiled <--    firstShow-      (compileProfile (objectProfileWithRules "generated" Any (Just provenanceMemberRules) Nothing))-  cid <- parseTestConceptId "thing"-  -- A well-formed mapping satisfies the rule and reports nothing at all, which-  -- is the half of the fix that the old `missing profile-required field:-  -- generated` transcript got wrong.-  wellFormed <--    profileConcept-      "thing"-      [ ("type", String "Thing"),-        ("generated", object ["by" .= ("human:nadeem" :: Text), "at" .= ("2026-06-18T00:00:00Z" :: Text)])-      ]-      "# Thing\n"-  assertEqual [] (validateProfile StrictAuthoring compiled [wellFormed])-  -- A mapping missing the demanded member reports that member, not the parent.-  missingMember <--    profileConcept-      "thing"-      [ ("type", String "Thing"),-        ("generated", object ["at" .= ("2026-06-18T00:00:00Z" :: Text)])-      ]-      "# Thing\n"-  assertEqual-    [MissingNestedProfileField cid (objectMemberPath "generated" "by") Nothing]-    (validateProfile PermissiveConformance compiled [missingMember])-  -- Members are value-checked exactly as list-element members are, and the-  -- recommended member is reported only under strict authoring.-  badTimestamp <--    profileConcept-      "thing"-      [("type", String "Thing"), ("generated", object ["by" .= ("human:nadeem" :: Text), "at" .= ("not-a-time" :: Text)])]-      "# Thing\n"-  assertEqual-    [ValueFormatMismatch cid (objectMemberPath "generated" "at") Rfc3339Utc (String "not-a-time")]-    (validateProfile PermissiveConformance compiled [badTimestamp])-  onlyBy <--    profileConcept-      "thing"-      [("type", String "Thing"), ("generated", object ["by" .= ("human:nadeem" :: Text)])]-      "# Thing\n"-  assertEqual [] (validateProfile PermissiveConformance compiled [onlyBy])-  assertEqual-    [MissingRecommendedNestedProfileField cid (objectMemberPath "generated" "at") Nothing]-    (validateProfile StrictAuthoring compiled [onlyBy])-  -- The key itself is still demanded when it is absent entirely, and an empty-  -- mapping counts as absent for the same reason an empty list does.-  absent <- profileConcept "thing" [("type", String "Thing")] "# Thing\n"-  assertEqual-    [MissingProfileField cid "generated" Nothing]-    (validateProfile PermissiveConformance compiled [absent])-  emptyMapping <--    profileConcept "thing" [("type", String "Thing"), ("generated", object [])] "# Thing\n"-  assertEqual-    [MissingProfileField cid "generated" Nothing]-    (validateProfile PermissiveConformance compiled [emptyMapping])---- | OKF v0.2 specification §5.2 permits @verified@ as a list of mappings or as--- one bare mapping and requires a consumer to treat the bare mapping as a--- one-element list. A rule declaring both shapes checks them against the same--- member rules, and neither spelling is a cardinality mismatch.-testValidateRecordOrList :: Either Text ()-testValidateRecordOrList = do-  compiled <--    firstShow-      ( compileProfile-          (objectProfileWithRules "verified" Any (Just provenanceMemberRules) (Just provenanceMemberRules))-      )-  cid <- parseTestConceptId "thing"-  bareMapping <--    profileConcept-      "thing"-      [("type", String "Thing"), ("verified", object ["at" .= ("2026-06-20T00:00:00Z" :: Text)])]-      "# Thing\n"-  assertEqual-    [MissingNestedProfileField cid (objectMemberPath "verified" "by") Nothing]-    (validateProfile PermissiveConformance compiled [bareMapping])-  oneElementList <--    profileConcept-      "thing"-      [("type", String "Thing"), ("verified", toJSON [object ["at" .= ("2026-06-20T00:00:00Z" :: Text)]])]-      "# Thing\n"-  assertEqual-    [ MissingNestedProfileField-        cid-        (FieldPath (FieldName "verified" :| [ArrayIndex 0, FieldName "by"]))-        Nothing-    ]-    (validateProfile PermissiveConformance compiled [oneElementList])-  -- Both spellings are satisfiable, and neither reports a shape error.-  goodMapping <--    profileConcept-      "thing"-      [("type", String "Thing"), ("verified", object ["by" .= ("human:nadeem" :: Text), "at" .= ("2026-06-20T00:00:00Z" :: Text)])]-      "# Thing\n"-  assertEqual [] (validateProfile StrictAuthoring compiled [goodMapping])---- | A shape error does not cascade: a value of the wrong shape produces exactly--- one 'CardinalityMismatch' naming the expected shape, and no member violations--- from walking a record that is not there.-testValidateObjectWrongShape :: Either Text ()-testValidateObjectWrongShape = do-  compiled <--    firstShow-      (compileProfile (objectProfileWithRules "generated" Any (Just provenanceMemberRules) Nothing))-  cid <- parseTestConceptId "thing"-  let listValue = toJSON [object ["by" .= ("human:nadeem" :: Text)]]-  concept <--    profileConcept "thing" [("type", String "Thing"), ("generated", listValue)] "# Thing\n"-  assertEqual-    [CardinalityMismatch cid (fieldPath "generated") Object listValue]-    (validateProfile StrictAuthoring compiled [concept])---- | Declaring no member rules at all still demands that the value be a mapping.--- This is how an author says "this key must be an object" and nothing more,--- which is the alternative to adding an @Object@ alternative to the published--- Dhall union.-testValidateEmptyObjectRules :: Either Text ()-testValidateEmptyObjectRules = do-  compiled <--    firstShow-      ( compileProfile-          ( objectProfileWithRules-              "generated"-              Any-              (Just (NestedRules {required = [], recommended = [], optional = []}))-              Nothing-          )-      )-  cid <- parseTestConceptId "thing"-  mapping <--    profileConcept-      "thing"-      [("type", String "Thing"), ("generated", object ["anything" .= ("at all" :: Text)])]-      "# Thing\n"-  assertEqual [] (validateProfile StrictAuthoring compiled [mapping])-  scalarValue <--    profileConcept "thing" [("type", String "Thing"), ("generated", String "nope")] "# Thing\n"-  assertEqual-    [CardinalityMismatch cid (fieldPath "generated") Object (String "nope")]-    (validateProfile PermissiveConformance compiled [scalarValue])--objectMemberPath :: Text -> Text -> FieldPath-objectMemberPath parent key = FieldPath (FieldName parent :| [FieldName key])--firstTypeRule :: ProfileSpec -> TypeRule-firstTypeRule spec =-  case spec ^. #types of-    rule : _ -> rule-    [] -> error "test profile unexpectedly has no type rules"--withTypeFrontmatter :: FrontmatterRules -> TypeRule -> TypeRule-withTypeFrontmatter-  replacement-  TypeRule-    { type_,-      description,-      guidance,-      pathPattern,-      resourceScheme,-      requireSchemaSection,-      schemaColumns,-      idPrefix-    } =-    TypeRule-      { type_,-        description,-        guidance,-        frontmatter = replacement,-        pathPattern,-        resourceScheme,-        requireSchemaSection,-        schemaColumns,-        idPrefix-      }--withTypeName :: Text -> TypeRule -> TypeRule-withTypeName-  replacement-  TypeRule-    { description,-      guidance,-      frontmatter,-      pathPattern,-      resourceScheme,-      requireSchemaSection,-      schemaColumns,-      idPrefix-    } =-    TypeRule-      { type_ = replacement,-        description,-        guidance,-        frontmatter,-        pathPattern,-        resourceScheme,-        requireSchemaSection,-        schemaColumns,-        idPrefix-      }--testProfileRulesApplyToUnknownTypes :: Either Text ()-testProfileRulesApplyToUnknownTypes = do-  compiled <- firstShow (compileProfile typeAwareProfileSpec)-  concept <- profileConcept "extensions/one" [("type", String "Extension Concept")] "# One\n"-  cid <- parseTestConceptId "extensions/one"-  assertEqual-    [MissingProfileField cid "title" Nothing]-    (validateProfile PermissiveConformance compiled [concept])--testStrictProfileRecommendations :: Either Text ()-testStrictProfileRecommendations = do-  compiled <- firstShow (compileProfile typeAwareProfileSpec)-  concept <--    profileConcept-      "owned/one"-      [("type", String "Owned Concept"), ("title", String "One"), ("owner", String "Ari")]-      "# One\n"-  cid <- parseTestConceptId "owned/one"-  assertEqual [] (validateProfile PermissiveConformance compiled [concept])-  assertEqual-    [MissingRecommendedProfileField cid "reviewer" Nothing]-    (validateProfile StrictAuthoring compiled [concept])---- | Build an in-memory concept from a raw ID, frontmatter pairs, and a body.-profileConcept :: Text -> [(Text, Value)] -> Text -> Either Text Concept-profileConcept rawId fieldPairs bodyText = do-  conceptId <- parseTestConceptId rawId-  pure (conceptFromDocument conceptId (OKFDocument (frontmatterFromFields fieldPairs) bodyText))---- | A well-formed @# Schema@ section matching the profile's required columns.-schemaSectionBody :: Text-schemaSectionBody =-  Text.unlines-    [ "# Schema",-      "",-      "| Column | Type   | Nullable | Description |",-      "|--------|--------|----------|-------------|",-      "| id     | bigint | no       | Primary key |"-    ]--testProfileConformingTable :: Either Text ()-testProfileConformingTable = do-  concept <--    profileConcept-      "schemas/sales/tables/orders"-      [ ("type", String "PostgreSQL Table"),-        ("title", String "Orders"),-        ("resource", String "postgresql://warehouse/sales/orders")-      ]-      schemaSectionBody-  assertEqual [] (validateTestProfile testProfileSpec [concept])--testProfileUnknownType :: Either Text ()-testProfileUnknownType = do-  concept <--    profileConcept-      "schemas/sales/tables/bad"-      [("type", String "pg table"), ("resource", String "postgresql://x")]-      schemaSectionBody-  cid <- parseTestConceptId "schemas/sales/tables/bad"-  assertEqual-    [TypeNotInProfile cid "pg table", MissingProfileField cid "title" Nothing]-    (validateTestProfile testProfileSpec [concept])--testProfileMissingField :: Either Text ()-testProfileMissingField = do-  concept <--    profileConcept-      "schemas/sales/tables/orders"-      [("type", String "PostgreSQL Table"), ("resource", String "postgresql://x")]-      schemaSectionBody-  cid <- parseTestConceptId "schemas/sales/tables/orders"-  assertEqual [MissingProfileField cid "title" Nothing] (validateTestProfile testProfileSpec [concept])--testProfileResourceMismatch :: Either Text ()-testProfileResourceMismatch = do-  concept <--    profileConcept-      "schemas/sales/tables/orders"-      [("type", String "PostgreSQL Table"), ("title", String "Orders"), ("resource", String "mysql://x")]-      schemaSectionBody-  cid <- parseTestConceptId "schemas/sales/tables/orders"-  assertEqual-    [ResourceSchemeMismatch cid "postgresql" "mysql://x"]-    (validateTestProfile testProfileSpec [concept])--testProfilePathMismatch :: Either Text ()-testProfilePathMismatch = do-  concept <--    profileConcept-      "tables/orders"-      [("type", String "PostgreSQL Table"), ("title", String "Orders"), ("resource", String "postgresql://x")]-      schemaSectionBody-  cid <- parseTestConceptId "tables/orders"-  assertEqual-    [PathPatternMismatch cid "PostgreSQL Table" "schemas/*/tables/*"]-    (validateTestProfile testProfileSpec [concept])--testProfileMissingSchema :: Either Text ()-testProfileMissingSchema = do-  concept <--    profileConcept-      "schemas/sales/tables/orders"-      [("type", String "PostgreSQL Table"), ("title", String "Orders"), ("resource", String "postgresql://x")]-      "# Overview\n\nNo schema section here.\n"-  cid <- parseTestConceptId "schemas/sales/tables/orders"-  assertEqual-    [MissingSchemaSection cid "PostgreSQL Table"]-    (validateTestProfile testProfileSpec [concept])--testProfileSchemaColumnsMismatch :: Either Text ()-testProfileSchemaColumnsMismatch = do-  let mismatchBody =-        Text.unlines-          ["# Schema", "", "| Col | Type |", "|-----|------|", "| id  | bigint |"]-  concept <--    profileConcept-      "schemas/sales/tables/orders"-      [("type", String "PostgreSQL Table"), ("title", String "Orders"), ("resource", String "postgresql://x")]-      mismatchBody-  cid <- parseTestConceptId "schemas/sales/tables/orders"-  assertEqual-    [SchemaColumnsMismatch cid "PostgreSQL Table" ["Column", "Type", "Nullable", "Description"] ["Col", "Type"]]-    (validateTestProfile testProfileSpec [concept])--testProfileConformingDocumentId :: Either Text ()-testProfileConformingDocumentId = do-  concept <--    profileConcept-      "decisions/one"-      [("type", String "Decision Record"), ("title", String "One"), ("docId", String "ADR-1")]-      "# One\n"-  assertEqual [] (validateTestProfile testDocumentIdProfileSpec [concept])--testProfileMissingDocumentId :: Either Text ()-testProfileMissingDocumentId = do-  concept <--    profileConcept-      "decisions/one"-      [("type", String "Decision Record"), ("title", String "One")]-      "# One\n"-  cid <- parseTestConceptId "decisions/one"-  assertEqual-    [MissingDocumentId cid "Decision Record" "ADR"]-    (validateTestProfile testDocumentIdProfileSpec [concept])--testProfileMalformedDocumentIds :: Either Text ()-testProfileMalformedDocumentIds = do-  leadingZero <--    profileConcept-      "decisions/leading-zero"-      [("type", String "Decision Record"), ("title", String "Leading zero"), ("docId", String "ADR-007")]-      "# Leading zero\n"-  wrongPrefix <--    profileConcept-      "decisions/wrong-prefix"-      [("type", String "Decision Record"), ("title", String "Wrong prefix"), ("docId", String "RFC-1")]-      "# Wrong prefix\n"-  leadingZeroId <- parseTestConceptId "decisions/leading-zero"-  wrongPrefixId <- parseTestConceptId "decisions/wrong-prefix"-  assertEqual-    [ MalformedDocumentId leadingZeroId "ADR" "ADR-007",-      MalformedDocumentId wrongPrefixId "ADR" "RFC-1"-    ]-    (validateTestProfile testDocumentIdProfileSpec [leadingZero, wrongPrefix])--testProfileDuplicateDocumentIds :: Either Text ()-testProfileDuplicateDocumentIds = do-  second <--    profileConcept-      "decisions/second"-      [("type", String "Decision Record"), ("title", String "Second"), ("docId", String "ADR-1")]-      "# Second\n"-  firstConcept <--    profileConcept-      "decisions/first"-      [("type", String "Decision Record"), ("title", String "First"), ("docId", String "ADR-1")]-      "# First\n"-  firstId <- parseTestConceptId "decisions/first"-  secondId <- parseTestConceptId "decisions/second"-  assertEqual-    [DuplicateDocumentId "ADR-1" firstId secondId]-    (validateTestProfile testDocumentIdProfileSpec [second, firstConcept])--testProfileDocumentIdsOffByDefault :: Either Text ()-testProfileDocumentIdsOffByDefault = do-  concept <--    profileConcept-      "schemas/sales/tables/orders"-      [ ("type", String "PostgreSQL Table"),-        ("title", String "Orders"),-        ("resource", String "postgresql://warehouse/sales/orders"),-        ("docId", String "not-a-handle")-      ]-      schemaSectionBody-  assertEqual [] (validateTestProfile testProfileSpec [concept])--testSchemaSectionColumns :: Either Text ()-testSchemaSectionColumns =-  assertEqual-    (Just ["Column", "Type", "Nullable", "Description"])-    (schemaSectionColumns schemaSectionBody)---- | Milestone 5: walking the deviating fixture and validating it against the--- shipped descriptor produces exactly the expected advisory deviations.-testProfileDeviationsFixture :: IO (Either Text ())-testProfileDeviationsFixture = do-  descriptorPath <- fixtureFilePath "profiles/postgresql.dhall"-  loaded <- loadProfileFile descriptorPath-  root <- fixturePath "profile-deviations"-  concepts <- readBundle root-  pure $ case loaded of-    Left err -> Left ("failed to load profile: " <> err)-    Right spec -> do-      badId <- parseTestConceptId "schemas/sales/tables/bad"-      ordersId <- parseTestConceptId "schemas/sales/tables/orders"-      assertEqual-        [TypeNotInProfile badId "pg table", MissingProfileField ordersId "title" Nothing]-        (validateTestProfile spec concepts)--testDocumentIdDeviationsFixture :: IO (Either Text ())-testDocumentIdDeviationsFixture = do-  descriptorPath <- fixtureFilePath "profiles/decisions.dhall"-  loaded <- loadProfileFile descriptorPath-  root <- fixturePath "doc-id-deviations"-  concepts <- readBundle root-  pure $ case loaded of-    Left err -> Left ("failed to load document ID profile: " <> err)-    Right spec -> do-      firstId <- parseTestConceptId "decisions/first"-      secondId <- parseTestConceptId "decisions/second"-      thirdId <- parseTestConceptId "decisions/third"-      fourthId <- parseTestConceptId "decisions/fourth"-      assertEqual-        [ MissingDocumentId fourthId "Decision Record" "ADR",-          MalformedDocumentId thirdId "ADR" "ADR-007",-          DuplicateDocumentId "ADR-1" firstId secondId-        ]-        (validateTestProfile spec concepts)--testTypeAwareProfileFixture :: IO (Either Text ())-testTypeAwareProfileFixture = do-  descriptorPath <- fixtureFilePath "profiles/type-frontmatter.dhall"-  loaded <- loadProfileFile descriptorPath-  root <- fixturePath "profile-type-frontmatter"-  concepts <- readBundle root-  pure $ case loaded of-    Left err -> Left ("failed to load type-aware profile: " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      ownedId <- parseTestConceptId "owned"-      assertEqual [] (validateProfile PermissiveConformance compiled concepts)-      assertEqual-        [MissingRecommendedProfileField ownedId "reviewer" Nothing]-        (validateProfile StrictAuthoring compiled concepts)---- | Declaration order is the author's; 'compiledProfileTypeNames' must not--- reorder it, because generated documentation follows it.-testCompiledProfileTypeNames :: IO (Either Text ())-testCompiledProfileTypeNames = do-  descriptorPath <- fixtureFilePath "profiles/type-frontmatter.dhall"-  loaded <- loadProfileFile descriptorPath-  pure $ case loaded of-    Left err -> Left ("failed to load type-aware profile: " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      assertEqual ["Owned Concept", "Open Concept"] (compiledProfileTypeNames compiled)---- | The merged view is what a reader of the profile actually needs: the type--- rule names two keys, but four apply.-testCompiledProfileRulesMergeTypeScope :: IO (Either Text ())-testCompiledProfileRulesMergeTypeScope = do-  descriptorPath <- fixtureFilePath "profiles/type-frontmatter.dhall"-  loaded <- loadProfileFile descriptorPath-  pure $ case loaded of-    Left err -> Left ("failed to load type-aware profile: " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      let owned = compiledProfileRulesForType compiled "Owned Concept"-      assertEqual ["owner", "reviewer", "title", "type"] (Map.keys owned)-      ownerRule <- lookupCompiledRule "owner" owned-      assertEqual [(RequiredField, Nothing)] (presenceSummary ownerRule)-      reviewerRule <- lookupCompiledRule "reviewer" owned-      assertEqual [(RecommendedField, Nothing)] (presenceSummary reviewerRule)-      titleRule <- lookupCompiledRule "title" owned-      assertEqual (Just "Human-readable concept title.") (fieldRuleDescription titleRule)-      assertEqual ["title", "type"] (Map.keys (compiledProfileRulesForType compiled "Open Concept"))-      assertEqual-        (compiledProfileBaseRules compiled)-        (compiledProfileRulesForType compiled "Not In Profile")---- | Pins the encoding an outside consumer is most likely to misread: @optional@--- is an empty presence-clause list, not a constructor.-testCompiledProfileOptionalPresence :: IO (Either Text ())-testCompiledProfileOptionalPresence = do-  descriptorPath <- fixtureFilePath "profiles/optional-fields.dhall"-  loaded <- loadProfileFile descriptorPath-  pure $ case loaded of-    Left err -> Left ("failed to load optional-field profile: " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      let rules = compiledProfileRulesForType compiled "Decision Record"-      for_ ["supersedes", "decidedAt", "reviews", "originatingPlan"] $ \key -> do-        rule <- lookupCompiledRule key rules-        assertEqual [] (presenceSummary rule)-      statusRule <- lookupCompiledRule "status" rules-      assertEqual [(RequiredField, Nothing)] (presenceSummary statusRule)-      assertEqual ["accepted", "superseded"] (fieldRuleAllowedValues statusRule)-      assertEqual Scalar (fieldRuleCardinality statusRule)-      supersededByRule <- lookupCompiledRule "supersededBy" rules-      assertEqual-        [(RequiredField, Just (FieldCondition "status" ["superseded"]))]-        (presenceSummary supersededByRule)-      supersedesRule <- lookupCompiledRule "supersedes" rules-      assertEqual-        (Just (handleReferenceRule "ADR" [] False))-        (fieldRuleReference supersedesRule)-      reviewsRule <- lookupCompiledRule "reviews" rules-      nested <- maybe (Left "reviews declares no element fields") Right (fieldRuleElementFields reviewsRule)-      assertEqual ["kind", "model"] (Map.keys nested)-      kindRule <- lookupCompiledRule "kind" nested-      assertEqual [(RequiredField, Nothing)] (presenceSummary kindRule)-      assertEqual Nothing (fieldRuleElementFields kindRule)-      modelRule <- lookupCompiledRule "model" nested-      assertEqual [] (presenceSummary modelRule)--lookupCompiledRule :: Text -> Map Text EffectiveFieldRule -> Either Text EffectiveFieldRule-lookupCompiledRule key rules =-  maybe (Left ("no compiled rule for key " <> key)) Right (Map.lookup key rules)---- | An 'EffectiveFieldRule' is abstract, so summarize its presence clauses--- through the public accessors into something comparable.-presenceSummary :: EffectiveFieldRule -> [(FieldRequirement, Maybe FieldCondition)]-presenceSummary rule =-  [ (presenceClauseRequirement clause, presenceClauseCondition clause)-  | clause <- fieldRulePresenceClauses rule-  ]---- * Profile documentation rendering---- | Load a fixture profile, compile it, render documentation, and hand both the--- compiled profile and the concepts to an assertion.-withRenderedProfileDocumentation ::-  FilePath ->-  DocumentationOptions ->-  (CompiledProfile -> [Concept] -> Either Text ()) ->-  IO (Either Text ())-withRenderedProfileDocumentation fixture options assertion = do-  descriptorPath <- fixtureFilePath fixture-  loaded <- loadProfileFile descriptorPath-  pure $ case loaded of-    Left err -> Left ("failed to load profile " <> Text.pack fixture <> ": " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      concepts <- firstShow (renderProfileDocumentation options compiled)-      assertion compiled concepts--conceptBodyLines :: Concept -> [Text]-conceptBodyLines concept = Text.lines (conceptDocument concept ^. #body)---- | Assert on whole lines rather than substrings, so a failure names the line--- that changed instead of pointing at an opaque haystack.-assertHasLine :: Text -> [Text] -> Either Text ()-assertHasLine expected bodyLines =-  assertBool-    ("expected body line " <> Text.pack (show expected))-    (expected `elem` bodyLines)--conceptAt :: Int -> [Concept] -> Either Text Concept-conceptAt offset concepts =-  case drop offset concepts of-    concept : _ -> Right concept-    [] -> Left ("no concept at position " <> Text.pack (show offset))--testProfileDocumentationSlug :: Either Text ()-testProfileDocumentationSlug = do-  assertEqual "bigquery-table" (profileDocumentationSlug "BigQuery Table")-  assertEqual "decision-record" (profileDocumentationSlug "Decision Record")-  assertEqual "c-header" (profileDocumentationSlug "C++ Header")-  assertEqual "spaced-out" (profileDocumentationSlug "  spaced  out  ")-  assertEqual "adr-7" (profileDocumentationSlug "ADR-7")-  assertEqual "" (profileDocumentationSlug "###")---- | A profile with no rules at all beyond a required @type@, used to exercise--- layout concerns without dragging in field rendering.-plainDocumentationTypeRule :: Text -> TypeRule-plainDocumentationTypeRule typeName =-  TypeRule-    { type_ = typeName,-      description = Nothing,-      guidance = Nothing,-      frontmatter = FrontmatterRules {required = [], recommended = [], optional = []},-      pathPattern = Nothing,-      resourceScheme = Nothing,-      requireSchemaSection = False,-      schemaColumns = [],-      idPrefix = Nothing-    }---- | Two distinct @type@ strings that slug identically, plus one that slugs to--- nothing at all. No shipped descriptor has this shape, so the spec is built in--- Haskell rather than by editing a fixture.-duplicateSlugProfileSpec :: ProfileSpec-duplicateSlugProfileSpec =-  ProfileSpec-    { name = "duplicate-slugs",-      description = Nothing,-      guidance = Nothing,-      okfVersion = "0.1",-      frontmatter =-        FrontmatterRules-          { required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing],-            recommended = [],-            optional = []-          },-      allowUnknownTypes = False,-      allowUnknownFields = True,-      idField = Nothing,-      requireBundleVersion = Nothing,-      types =-        [ plainDocumentationTypeRule "Decision Record",-          plainDocumentationTypeRule "decision record",-          plainDocumentationTypeRule "###"-        ]-    }--testProfileDocumentationSlugCollisions :: Either Text ()-testProfileDocumentationSlugCollisions = do-  compiled <- firstShow (compileProfile duplicateSlugProfileSpec)-  concepts <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)-  assertEqual-    ["profile", "types/decision-record", "types/decision-record-2", "types/type-3"]-    (map (renderConceptId . conceptIdOf) concepts)--testProfileValueDisplayNames :: Either Text ()-testProfileValueDisplayNames = do-  assertEqual "any" (renderCardinalityName Any)-  assertEqual "scalar" (renderCardinalityName Scalar)-  assertEqual "list" (renderCardinalityName List)-  assertEqual "rfc3339-utc" (renderFieldFormatName Rfc3339Utc)-  assertEqual "date" (renderFieldFormatName Date)-  assertEqual "uri" (renderFieldFormatName Uri)-  assertEqual "uri-with-scheme(mori)" (renderFieldFormatName (UriWithScheme "mori"))-  assertEqual "document-handle(ADR)" (renderFieldFormatName (DocumentHandle "ADR"))--testProfileDocumentationRootConcept :: IO (Either Text ())-testProfileDocumentationRootConcept =-  withRenderedProfileDocumentation-    "profiles/optional-fields.dhall"-    defaultDocumentationOptions-    ( \compiled concepts -> do-        assertEqual (1 + length (compiledProfileTypeNames compiled)) (length concepts)-        root <- conceptAt 0 concepts-        assertEqual "profile" (renderConceptId (conceptIdOf root))-        assertEqual profileConceptType (conceptType root)-        assertEqual (Just "optional-fields") (conceptTitle root)-        let bodyLines = conceptBodyLines root-        assertHasLine "# optional-fields" bodyLines-        assertHasLine "- [Decision Record](/types/decision-record.md)" bodyLines-        assertHasLine "- Document ID field: `docId`" bodyLines-        assertHasLine "- Unknown concept types: rejected" bodyLines-        assertHasLine "- Unknown frontmatter keys: rejected" bodyLines-        -- Every profile-level setting has a bullet whether or not the profile-        -- sets it, so a reader learns the setting exists and that this profile-        -- leaves it alone. This fixture declares no bundle-version requirement.-        assertHasLine "- Required bundle version: none" bodyLines-    )---- | A profile setting the renderer does not print is a silent hole in generated--- documentation, so @requireBundleVersion@ is rendered in the same change that--- adds it — the rule stated in--- @docs\/adr\/11-growing-the-profile-descriptor-language.md@.-testProfileDocumentationRequiredBundleVersion :: Either Text ()-testProfileDocumentationRequiredBundleVersion = do-  compiled <- firstShow (compileProfile (requireBundleVersionProfile (Just "0.2")))-  concepts <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)-  root <- conceptAt 0 concepts-  assertHasLine "- Required bundle version: `0.2`" (conceptBodyLines root)---- | A rule kind the renderer does not know about is a silent hole in generated--- profile documentation, so object rules are rendered in the same change that--- creates them. The bullet list is fixed by design, so a key that declares no--- object shape says so explicitly rather than omitting the bullet.-testProfileDocumentationObjectFields :: Either Text ()-testProfileDocumentationObjectFields = do-  compiled <--    firstShow-      (compileProfile (objectProfileWithRules "generated" Any (Just provenanceMemberRules) Nothing))-  concepts <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)-  root <- conceptAt 0 concepts-  let bodyLines = conceptBodyLines root-  assertHasLine "- Object fields:" bodyLines-  assertHasLine-    "    - `by` — required; allowed values: any; cardinality: any; format: none — Who or what produced this content."-    bodyLines-  assertHasLine-    "    - `at` — recommended; allowed values: any; cardinality: any; format: rfc3339-utc"-    bodyLines-  assertHasLine "- Element fields: none" bodyLines-  assertHasLine "- Cardinality: object" bodyLines-  -- A key with no object shape still carries the bullet, so the shape of the-  -- list never shifts between rules.-  assertHasLine "- Object fields: none" bodyLines---- | Nested reference and parent uniqueness policies are compiled constraints,--- so generated documentation must expose both rather than silently dropping--- the rule kind that lives below the top-level field.-testProfileDocumentationNestedReferenceAndUniqueness :: IO (Either Text ())-testProfileDocumentationNestedReferenceAndUniqueness =-  withRenderedProfileDocumentation-    "profiles/nested-references-and-uniqueness.dhall"-    defaultDocumentationOptions-    ( \_compiled concepts -> do-        typeConcept <- conceptAt 1 concepts-        let bodyLines = conceptBodyLines typeConcept-        assertHasLine-          "    - `ref` — required; allowed values: any; cardinality: scalar; format: none; reference: local handles with prefix `IR`; external URIs with scheme `mori`; local handles prohibited; self-reference not allowed; external URI whole-value pattern `mori://[^/]+/[^/]+/okf/improvement-requests/concepts/IR-[1-9][0-9]*`"-          bodyLines-        assertHasLine "- Unique by: `id`" bodyLines-    )--testProfileDocumentationTypeConcept :: IO (Either Text ())-testProfileDocumentationTypeConcept =-  withRenderedProfileDocumentation-    "profiles/optional-fields.dhall"-    defaultDocumentationOptions-    ( \_compiled concepts -> do-        typeConcept <- conceptAt 1 concepts-        assertEqual "types/decision-record" (renderConceptId (conceptIdOf typeConcept))-        assertEqual profileTypeConceptType (conceptType typeConcept)-        assertEqual (Just "Decision Record") (conceptTitle typeConcept)-        let bodyLines = conceptBodyLines typeConcept-        assertHasLine "# Decision Record" bodyLines-        assertHasLine "Declared by the [optional-fields](/profile.md) profile." bodyLines-        assertHasLine "- Document ID prefix: `ADR`" bodyLines-        assertHasLine "- Path pattern: `decisions/*`" bodyLines-        assertHasLine "#### `status` — required" bodyLines-        assertHasLine "#### `supersededBy` — required when `status` is `superseded`" bodyLines-        assertHasLine "- Allowed values: `accepted`, `superseded`" bodyLines-        assertHasLine "#### `reviewedBy` — recommended" bodyLines-        assertHasLine "- Checked only under `--strict`" bodyLines-        assertHasLine "- Format: rfc3339-utc" bodyLines-        assertHasLine-          "    - `kind` — required; allowed values: `human`, `model`; cardinality: scalar; format: none"-          bodyLines-        assertHasLine-          "- Reference: local handles with prefix `ADR`; external URIs not allowed; local handles allowed; self-reference not allowed"-          bodyLines-        -- The profile-scope optional key must appear on the type page, under-        -- Optional: this is the merge being visible, which is the whole point.-        optionalHeading <- lineIndex "### Optional" bodyLines-        inheritedKey <- lineIndex "#### `originatingPlan` — optional" bodyLines-        assertBool-          "profile-scope optional key falls under the Optional heading"-          (optionalHeading < inheritedKey)-    )-  where-    lineIndex needle bodyLines =-      case List.elemIndex needle bodyLines of-        Just found -> Right found-        Nothing -> Left ("expected body line " <> Text.pack (show needle))--testProfileDocumentationInheritedRules :: IO (Either Text ())-testProfileDocumentationInheritedRules =-  withRenderedProfileDocumentation-    "profiles/type-frontmatter.dhall"-    defaultDocumentationOptions-    ( \_compiled concepts -> do-        assertEqual-          ["profile", "types/owned-concept", "types/open-concept"]-          (map (renderConceptId . conceptIdOf) concepts)-        owned <- conceptAt 1 concepts-        assertHasLine "#### `owner` — required" (conceptBodyLines owned)-        assertHasLine "#### `reviewer` — recommended" (conceptBodyLines owned)-        -- "Open Concept" declares no frontmatter of its own, so everything on-        -- its page is inherited from profile scope.-        open <- conceptAt 2 concepts-        let openBody = conceptBodyLines open-        assertEqual (Just "Open Concept") (conceptTitle open)-        assertHasLine "#### `title` — required" openBody-        assertHasLine "#### `type` — required" openBody-        assertHasLine "### Recommended" openBody-        assertHasLine "(none)" openBody-    )---- | Root documentation carries profile guidance once, while type pages expose--- the effective authoring procedure in profile-wide then type-specific order.--- Blank values behave like absence, and guidance stays in Markdown body text--- rather than leaking into generated frontmatter.-testProfileDocumentationGuidance :: IO (Either Text ())-testProfileDocumentationGuidance = do-  descriptorPath <- fixtureFilePath "profiles/guidance.dhall"-  loaded <- loadProfileFile descriptorPath-  pure $ do-    spec <- first ("failed to load guidance profile: " <>) loaded-    combined <- render spec-    combinedRoot <- conceptAt 0 combined-    combinedApi <- conceptAt 1 combined-    combinedFeature <- conceptAt 2 combined-    assertContains-      "root guidance follows description and precedes settings"-      ( "Authoring conventions for executable QA runbooks.\n\n"-          <> "## Guidance\n\n"-          <> profileProse-          <> "\n\n## Settings"-      )-      (conceptBody combinedRoot)-    assertContains-      "API guidance renders profile-wide before type-specific prose"-      ( "## Guidance\n\n"-          <> "### Profile-wide\n\n"-          <> profileProse-          <> "\n\n### Type-specific\n\n"-          <> apiProse-          <> "\n\n## Type settings"-      )-      (conceptBody combinedApi)-    assertContains-      "Feature guidance renders profile-wide before the event-stream procedure"-      ( "## Guidance\n\n"-          <> "### Profile-wide\n\n"-          <> profileProse-          <> "\n\n### Type-specific\n\n"-          <> featureProse-          <> "\n\n## Type settings"-      )-      (conceptBody combinedFeature)-    for_ combined $ \concept ->-      assertEqual-        Nothing-        (frontmatterLookup "guidance" (conceptDocument concept ^. #frontmatter))--    profileOnly <- render (spec & #types %~ map clearGuidance)-    profileOnlyApi <- conceptAt 1 profileOnly-    assertContains-      "profile-only type page labels its one effective scope"-      ("## Guidance\n\n### Profile-wide\n\n" <> profileProse <> "\n\n## Type settings")-      (conceptBody profileOnlyApi)-    assertOmits "profile-only type page omits the absent type scope" "### Type-specific" (conceptBody profileOnlyApi)--    typeOnly <- render (spec & #guidance .~ Nothing)-    typeOnlyRoot <- conceptAt 0 typeOnly-    typeOnlyApi <- conceptAt 1 typeOnly-    assertOmits "type-only profile page omits guidance" "## Guidance" (conceptBody typeOnlyRoot)-    assertContains-      "type-only type page labels its one effective scope"-      ("## Guidance\n\n### Type-specific\n\n" <> apiProse <> "\n\n## Type settings")-      (conceptBody typeOnlyApi)-    assertOmits "type-only type page omits the absent profile scope" "### Profile-wide" (conceptBody typeOnlyApi)--    blank <--      render-        ( spec-            & #guidance-            .~ Just " \n\t\n"-            & #types-            %~ map (setGuidance (Just "\n  \n"))-        )-    for_ blank $ \concept ->-      assertOmits "blank guidance omits the section" "## Guidance" (conceptBody concept)--    absent <--      render-        ( spec-            & #guidance-            .~ Nothing-            & #types-            %~ map clearGuidance-        )-    for_ absent $ \concept ->-      assertOmits "absent guidance omits the section" "## Guidance" (conceptBody concept)-  where-    profileProse =-      "Record the setup, cleanup, and evidence for every run.\n\nKeep supporting checks in source control and make the observed result reproducible."-    apiProse =-      "Add a source-controlled Hurl file that exercises the successful response and important failure responses.\n\nRun the Hurl file and retain the useful output as evidence."-    featureProse =-      "Exercise the public behavior, then inspect the generated domain-event stream.\n\nVerify event types, payloads, ordering, and stream identity, then verify the externally observable result."-    clearGuidance :: TypeRule -> TypeRule-    clearGuidance rule = rule & #guidance .~ Nothing-    setGuidance :: Maybe Text -> TypeRule -> TypeRule-    setGuidance value rule = rule & #guidance .~ value-    render spec = do-      compiled <- firstShow (compileProfile spec)-      firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)-    conceptBody concept = conceptDocument concept ^. #body-    assertContains label needle haystack =-      assertBool label (needle `Text.isInfixOf` haystack)-    assertOmits label needle haystack =-      assertBool label (not (needle `Text.isInfixOf` haystack))--testProfileDocumentationRoundTrip :: IO (Either Text ())-testProfileDocumentationRoundTrip =-  withRenderedProfileDocumentation-    "profiles/optional-fields.dhall"-    defaultDocumentationOptions-    ( \_compiled concepts ->-        for_ concepts $ \concept -> do-          reparsed <- firstShow (parseDocument (serializeConcept concept))-          assertEqual (conceptDocument concept) reparsed-    )--testProfileDocumentationValidates :: IO (Either Text ())-testProfileDocumentationValidates = do-  permissive <--    withRenderedProfileDocumentation-      "profiles/optional-fields.dhall"-      defaultDocumentationOptions-      (\_compiled concepts -> assertEqual [] (validateInMemoryBundle PermissiveConformance VersionUndeclared concepts))-  -- The default options carry a @generated@ family, so strict validation of-  -- default output passes with no extra flag: that is the whole point of the-  -- default. The v0.1 @timestamp@ spelling still satisfies strict authoring too.-  strictResult <--    withRenderedProfileDocumentation-      "profiles/optional-fields.dhall"-      defaultDocumentationOptions-      (\_compiled concepts -> assertEqual [] (validateInMemoryBundle StrictAuthoring VersionUndeclared concepts))-  strictLegacyResult <--    withRenderedProfileDocumentation-      "profiles/optional-fields.dhall"-      defaultDocumentationOptions {generated = Nothing, timestamp = Just "2026-07-31T00:00:00Z"}-      (\_compiled concepts -> assertEqual [] (validateInMemoryBundle StrictAuthoring VersionUndeclared concepts))-  pure (permissive >> strictResult >> strictLegacyResult)---- | Re-parse the serialized document, so the assertion proves the family--- survives serialization rather than merely living in the in-memory value.-reparsedGenerated :: Concept -> Either Text (Maybe Generated)-reparsedGenerated concept = do-  reparsed <- firstShow (parseDocument (serializeConcept concept))-  pure (readGenerated (reparsed ^. #frontmatter))--testProfileDocumentationDefaultGenerated :: IO (Either Text ())-testProfileDocumentationDefaultGenerated =-  withRenderedProfileDocumentation-    "profiles/optional-fields.dhall"-    defaultDocumentationOptions-    ( \_compiled concepts -> for_ concepts $ \concept -> do-        assertEqual-          (Just (Generated (ProcessActor "okf-profile-document") Nothing))-          (conceptGenerated concept)-        roundTripped <- reparsedGenerated concept-        assertEqual-          (Just (Generated (ProcessActor "okf-profile-document") Nothing))-          roundTripped-    )--testProfileDocumentationExplicitGenerated :: IO (Either Text ())-testProfileDocumentationExplicitGenerated =-  withRenderedProfileDocumentation-    "profiles/optional-fields.dhall"-    defaultDocumentationOptions-      { generated = Just (Generated (HumanActor "nadeem") (Just "2026-08-01T00:00:00Z"))-      }-    ( \_compiled concepts -> for_ concepts $ \concept -> do-        roundTripped <- reparsedGenerated concept-        assertEqual-          (Just (Generated (HumanActor "nadeem") (Just "2026-08-01T00:00:00Z")))-          roundTripped-    )---- | The escape hatch: a caller who wants no provenance at all gets none.-testProfileDocumentationOmittedGenerated :: IO (Either Text ())-testProfileDocumentationOmittedGenerated =-  withRenderedProfileDocumentation-    "profiles/optional-fields.dhall"-    defaultDocumentationOptions {generated = Nothing}-    ( \_compiled concepts -> for_ concepts $ \concept -> do-        assertEqual Nothing (conceptGenerated concept)-        roundTripped <- reparsedGenerated concept-        assertEqual Nothing roundTripped-    )--testProfileDocumentationLinksResolve :: IO (Either Text ())-testProfileDocumentationLinksResolve =-  withRenderedProfileDocumentation-    "profiles/optional-fields.dhall"-    defaultDocumentationOptions-    ( \_compiled concepts -> do-        assertEqual [] (danglingReferences concepts)-        rootId <- parseTestConceptId "profile"-        typeId <- parseTestConceptId "types/decision-record"-        let graphEdges = buildGraph concepts ^. #edges-        assertBool-          "profile links to the type document"-          (Edge rootId typeId `elem` graphEdges)-        assertBool-          "the type document links back to the profile"-          (Edge typeId rootId `elem` graphEdges)-    )--testProfileDocumentationByteStable :: IO (Either Text ())-testProfileDocumentationByteStable = do-  descriptorPath <- fixtureFilePath "profiles/optional-fields.dhall"-  loaded <- loadProfileFile descriptorPath-  pure $ case loaded of-    Left err -> Left ("failed to load optional-field profile: " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      firstRender <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)-      secondRender <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)-      assertEqual firstRender secondRender-      -- Compare the serialized text too: serializeDocument sorts frontmatter-      -- keys, so a Concept-only comparison would miss a nondeterministic-      -- serialization.-      assertEqual (map serializeConcept firstRender) (map serializeConcept secondRender)---- | The generated bundle must survive the round trip the next plan's @--write@--- mode performs: write it out, generate indexes over it, walk it back.-testProfileDocumentationFilesystemRoundTrip :: IO (Either Text ())-testProfileDocumentationFilesystemRoundTrip = do-  descriptorPath <- fixtureFilePath "profiles/optional-fields.dhall"-  loaded <- loadProfileFile descriptorPath-  case loaded >>= (firstShow . compileProfile) of-    Left err -> pure (Left ("failed to prepare optional-field profile: " <> err))-    Right compiled ->-      case renderProfileDocumentation defaultDocumentationOptions compiled of-        Left err -> pure (Left ("render failed: " <> Text.pack (show err)))-        Right concepts -> do-          temporaryDirectory <- getTemporaryDirectory-          root <- createTempDirectory temporaryDirectory "okf-profile-documentation"-          writeBundle root concepts-          indexResult <- writeBundleIndexes root-          walked <- walkBundle root-          removeDirectoryRecursive root-          pure $ do-            _ <- firstShow indexResult-            walkedConcepts <- firstShow walked-            assertEqual-              (List.sort (map (renderConceptId . conceptIdOf) concepts))-              (List.sort (map (renderConceptId . conceptIdOf) walkedConcepts))--testClosedFieldsFixture :: IO (Either Text ())-testClosedFieldsFixture = do-  descriptorPath <- fixtureFilePath "profiles/closed-fields.dhall"-  loaded <- loadProfileFile descriptorPath-  root <- fixturePath "profile-closed-fields"-  concepts <- readBundle root-  pure $ case loaded of-    Left err -> Left ("failed to load closed-field profile: " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      typoId <- parseTestConceptId "requests/typo"-      assertEqual-        [MissingProfileField typoId "status" Nothing, FieldNotInProfile typoId "stauts"]-        (validateProfile PermissiveConformance compiled concepts)--testCardinalityFixture :: IO (Either Text ())-testCardinalityFixture = do-  descriptorPath <- fixtureFilePath "profiles/cardinality.dhall"-  loaded <- loadProfileFile descriptorPath-  root <- fixturePath "profile-cardinality"-  concepts <- readBundle root-  pure $ case loaded of-    Left err -> Left ("failed to load cardinality profile: " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      badId <- parseTestConceptId "bad"-      assertEqual-        [ CardinalityMismatch badId (fieldPath "tags") List (String "one"),-          CardinalityMismatch badId (fieldPath "title") Scalar (toJSON (["One", "Two"] :: [Text]))-        ]-        (validateProfile PermissiveConformance compiled concepts)--testFormatsFixture :: IO (Either Text ())-testFormatsFixture = do-  descriptorPath <- fixtureFilePath "profiles/formats.dhall"-  loaded <- loadProfileFile descriptorPath-  root <- fixturePath "profile-formats"-  concepts <- readBundle root-  pure $ case loaded of-    Left err -> Left ("failed to load format profile: " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      badId <- parseTestConceptId "bad"-      assertEqual-        [ ValueFormatMismatch badId (fieldPath "docId") (DocumentHandle "ADR") (String "ADR-007"),-          ValueFormatMismatch badId (fieldPath "homepage") (UriWithScheme "https") (String "mailto:owner@example.test"),-          ValueFormatMismatch badId (fieldPath "links") Uri (toJSON (["https://example.test/good", "https://example.test/bad%ZZ"] :: [Text])),-          ValueFormatMismatch badId (fieldPath "published") Date (String "2026-13-45"),-          ValueFormatMismatch badId (fieldPath "timestamp") Rfc3339Utc (String "2026-07-29T17:00:00+01:00")-        ]-        (validateProfile PermissiveConformance compiled concepts)--testNestedReviewsFixture :: IO (Either Text ())-testNestedReviewsFixture = do-  descriptorPath <- fixtureFilePath "profiles/nested-reviews.dhall"-  loaded <- loadProfileFile descriptorPath-  root <- fixturePath "profile-nested-reviews"-  concepts <- readBundle root-  pure $ case loaded of-    Left err -> Left ("failed to load nested review profile: " <> err)-    Right spec -> do-      compiled <- firstShow (compileProfile spec)-      badId <- parseTestConceptId "bad"-      let permissiveExpected =-            [ NestedElementNotRecord badId (FieldPath (FieldName "reviews" :| [ArrayIndex 1])) (String "not-a-record"),-              CardinalityMismatch badId (nestedTestPath 2 "context") Scalar (toJSON (["wrong"] :: [Text])),-              MissingNestedProfileField badId (nestedTestPath 2 "outcome") Nothing,-              ValueFormatMismatch badId (nestedTestPath 2 "reviewed_at") Rfc3339Utc (String "2026-13-45T99:99:99Z"),-              ValueNotInVocabulary badId (nestedTestPath 2 "scope") reviewScopes (String "invalid")-            ]-      assertEqual permissiveExpected (validateProfile PermissiveConformance compiled concepts)-      assertEqual-        [ NestedElementNotRecord badId (FieldPath (FieldName "reviews" :| [ArrayIndex 1])) (String "not-a-record"),-          CardinalityMismatch badId (nestedTestPath 2 "context") Scalar (toJSON (["wrong"] :: [Text])),-          MissingRecommendedNestedProfileField badId (nestedTestPath 2 "notes") Nothing,-          MissingNestedProfileField badId (nestedTestPath 2 "outcome") Nothing,-          ValueFormatMismatch badId (nestedTestPath 2 "reviewed_at") Rfc3339Utc (String "2026-13-45T99:99:99Z"),-          ValueNotInVocabulary badId (nestedTestPath 2 "scope") reviewScopes (String "invalid")-        ]-        (validateProfile StrictAuthoring compiled concepts)--testConditionalFieldsFixture :: IO (Either Text ())-testConditionalFieldsFixture = do-  descriptorPath <- fixtureFilePath "profiles/conditional-fields.dhall"-  invalidDescriptorPath <- fixtureFilePath "profiles/conditional-fields-invalid.dhall"-  loaded <- loadProfileFile descriptorPath-  invalidLoaded <- loadProfileFile invalidDescriptorPath-  root <- fixturePath "profile-conditions"-  concepts <- readBundle root-  pure $ do-    spec <- first ("failed to load conditional profile: " <>) loaded-    compiled <- firstShow (compileProfile spec)-    invalidSpec <- first ("failed to load invalid conditional profile: " <>) invalidLoaded-    decisionsMissingStatus <- parseTestConceptId "decisions/missing-status"-    decisionsSuperseded <- parseTestConceptId "decisions/superseded"-    postgresqlOperational <- parseTestConceptId "postgresql/operational"-    postgresqlProjection <- parseTestConceptId "postgresql/projection"-    reviewsMixed <- parseTestConceptId "reviews/mixed"-    assertEqual-      ( Left-          ( ConditionFieldHasUnreachableValues-              Nothing-              (fieldPath "supersededBy")-              (fieldPath "status")-              ["superseded"]-              ["active"]-              :| []-          )-      )-      (compileProfile invalidSpec)-    assertEqual-      [ MissingProfileField decisionsMissingStatus "status" Nothing,-        MissingProfileField decisionsSuperseded "supersededBy" (Just (FieldCondition "status" ["superseded"])),-        MissingProfileField postgresqlProjection "sourceQuery" (Just (FieldCondition "derivationKind" ["projection"])),-        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "effort") (Just (FieldCondition "kind" ["model"])),-        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "model") (Just (FieldCondition "kind" ["model"])),-        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "provider") (Just (FieldCondition "kind" ["model"]))-      ]-      (validateProfile PermissiveConformance compiled concepts)-    assertEqual-      [ MissingProfileField decisionsMissingStatus "status" Nothing,-        MissingProfileField decisionsSuperseded "supersededBy" (Just (FieldCondition "status" ["superseded"])),-        MissingRecommendedProfileField postgresqlOperational "runbook" (Just (FieldCondition "derivationKind" ["operational"])),-        MissingProfileField postgresqlProjection "sourceQuery" (Just (FieldCondition "derivationKind" ["projection"])),-        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "effort") (Just (FieldCondition "kind" ["model"])),-        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "model") (Just (FieldCondition "kind" ["model"])),-        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "provider") (Just (FieldCondition "kind" ["model"]))-      ]-      (validateProfile StrictAuthoring compiled concepts)-  where-    nestedReviewPath elementIndex key =-      FieldPath (FieldName "reviews" :| [ArrayIndex elementIndex, FieldName key])--testDocumentReferencesFixture :: IO (Either Text ())-testDocumentReferencesFixture = do-  descriptorPath <- fixtureFilePath "profiles/document-references.dhall"-  invalidDescriptorPath <- fixtureFilePath "profiles/document-references-invalid.dhall"-  loaded <- loadProfileFile descriptorPath-  invalidLoaded <- loadProfileFile invalidDescriptorPath-  root <- fixturePath "profile-document-references"-  concepts <- readBundle root-  pure $ do-    spec <- first ("failed to load document-reference profile: " <>) loaded-    compiled <- firstShow (compileProfile spec)-    invalidSpec <- first ("failed to load invalid document-reference profile: " <>) invalidLoaded-    case compileProfile invalidSpec of-      Left _ -> Right ()-      Right _ -> Left "expected invalid document-reference descriptor to fail compilation"-    duplicateAId <- parseTestConceptId "decisions/duplicate-a"-    duplicateBId <- parseTestConceptId "decisions/duplicate-b"-    sourceId <- parseTestConceptId "decisions/source"-    assertEqual-      [ DanglingHandleReference sourceId (indexedPath 1) "ADR-99",-        ReferenceHandlePrefixMismatch sourceId (indexedPath 2) "PAT-3" "ADR",-        MalformedDocumentReference sourceId (indexedPath 3) (String "not a reference"),-        ExternalReferenceSchemeNotAllowed sourceId (indexedPath 4) "https" ["mori"],-        SelfDocumentReference sourceId (indexedPath 6) "ADR-1",-        MalformedDocumentReference sourceId (indexedPath 7) (Number 7),-        DuplicateDocumentId "ADR-3" duplicateAId duplicateBId-      ]-      (validateProfile PermissiveConformance compiled concepts)-  where-    indexedPath elementIndex = FieldPath (FieldName "references" :| [ArrayIndex elementIndex])--validateTestProfile :: ProfileSpec -> [Concept] -> [ProfileViolation]-validateTestProfile spec concepts =-  case compileProfile spec of-    Left errors -> error ("test profile failed to compile: " <> show errors)-    Right compiled -> validateProfile PermissiveConformance compiled concepts--substringIndex :: Text -> Text -> Maybe Int-substringIndex needle haystack =-  let (prefix, match) = Text.breakOn needle haystack-   in if Text.null match then Nothing else Just (Text.length prefix)--strictlyIncreasing :: [Int] -> Bool-strictlyIncreasing xs = and (zipWith (<) xs (drop 1 xs))--sampleDocument :: Text-sampleDocument =-  Text.unlines-    [ "---",-      "type: BigQuery Table",-      "title: Users",-      "description: User records.",-      "timestamp: 2026-06-16T00:00:00Z",-      "tags: [users]",-      "---",-      "",-      "# Schema",-      "",-      "Body text."-    ]--assertEqual :: (Eq value, Show value) => value -> value -> Either Text ()-assertEqual expected actual-  | expected == actual = Right ()-  | otherwise =-      Left-        ( "expected "-            <> Text.pack (show expected)-            <> ", got "-            <> Text.pack (show actual)-        )--assertBool :: Text -> Bool -> Either Text ()-assertBool _ True = Right ()-assertBool label False = Left label--firstShow :: (Show err) => Either err value -> Either Text value-firstShow =-  either (Left . Text.pack . show) Right--readBundle :: FilePath -> IO [Concept]-readBundle root = do-  result <- walkBundle root-  case result of-    Left bundleError -> fail (show bundleError)-    Right concepts -> pure concepts---- | Every file the bundle holds, for the path-valued frontmatter check.-readBundleInventory :: FilePath -> IO BundleInventory-readBundleInventory root = do-  result <- walkBundleInventory root-  case result of-    Left bundleError -> fail (show bundleError)-    Right inventory -> pure inventory---- | 'validateBundle' over a bundle assembled in memory, whose inventory is--- exactly the concepts' own source paths. Used wherever a test builds concepts--- rather than walking a directory; a test that does have a root passes--- 'readBundleInventory' instead, so the non-Markdown files are seen.-validateInMemoryBundle :: ValidationProfile -> VersionDeclaration -> [Concept] -> [BundleValidationError]-validateInMemoryBundle profile declaration concepts =-  validateBundle profile declaration (bundleInventoryOfConcepts concepts) concepts---- | The filter grammar @okf concepts@ hands to 'parseFieldEquals': one @=@, and--- a key that is either top-level or one level deep.-testParseConceptFilters :: Either Text ()-testParseConceptFilters = do-  assertEqual-    (Right (FieldEquals (TopLevelField "status") "accepted"))-    (parseFieldEquals "status=accepted")-  assertEqual-    (Right (FieldEquals (NestedField "reviews" "outcome") "approved"))-    (parseFieldEquals "reviews.outcome=approved")-  -- Split on the first '=' only, so a value carrying its own survives intact.-  assertEqual-    (Right (FieldEquals (TopLevelField "resource") "postgres://host/db?a=b"))-    (parseFieldEquals "resource=postgres://host/db?a=b")-  -- The value is verbatim: whitespace in a shell argument was typed on purpose.-  assertEqual-    (Right (FieldEquals (TopLevelField "title") " "))-    (parseFieldEquals "title= ")-  assertEqual (Left (MissingFilterSeparator "status")) (parseFieldEquals "status")-  assertEqual (Left (FilterKeyTooDeep "a.b.c")) (parseFieldSelector "a.b.c")-  assertEqual (Left EmptyFilterKey) (parseFieldSelector ".x")-  assertEqual (Left EmptyFilterKey) (parseFieldSelector "reviews.")-  assertEqual (Left EmptyFilterKey) (parseFieldSelector "")-  -- Rendering is the inverse a diagnostic quotes back.-  assertEqual "status=accepted" (renderFilter (FieldEquals (TopLevelField "status") "accepted"))-  assertEqual "reviews.outcome" (renderFieldSelector (NestedField "reviews" "outcome"))-  assertEqual "completedAt" (renderFilter (FieldPresent (TopLevelField "completedAt")))-  assertEqual "!status" (renderFilter (FieldAbsent (TopLevelField "status")))---- | A filter compares against text, so every non-textual scalar needs a--- spelling. Aeson writes an integral number without a trailing @.0@, which is--- what makes @--where usage_count=12@ match a YAML @usage_count: 12@.-testQueryScalarText :: Either Text ()-testQueryScalarText = do-  assertEqual (Just "accepted") (scalarText (String "accepted"))-  assertEqual (Just "12") (scalarText (Number 12))-  assertEqual (Just "0.5") (scalarText (Number 0.5))-  assertEqual (Just "true") (scalarText (Bool True))-  assertEqual Nothing (scalarText Null)-  assertEqual Nothing (scalarText (toJSON (["a", "b"] :: [Text])))-  assertEqual Nothing (scalarText (object ["by" .= ("human:nadeem" :: Text)]))---- | 'filterConcepts' over the concept-filter fixture bundle, which is built so--- that every matching shape appears exactly once: a key present on some--- concepts and absent on another, a list-valued key with more elements than the--- filter names, a nested key inside a list of records whose elements disagree,--- and a nested key inside a plain record.-testFilterConceptsOverFixture :: IO (Either Text ())-testFilterConceptsOverFixture = do-  root <- fixturePath "concept-filters"-  concepts <- readBundle root-  pure $ do-    let selected filters = renderConceptId . conceptIdOf <$> filterConcepts filters concepts-    assertEqual-      ["notes/scratch", "requests/alpha", "requests/beta", "requests/gamma"]-      (selected [])-    assertEqual ["requests/alpha"] (selected [FieldEquals (TopLevelField "status") "accepted"])-    -- Existential over a list: alpha is tagged [profiles, cli] and still matches.-    assertEqual-      ["requests/alpha", "requests/beta"]-      (selected [FieldEquals (TopLevelField "tags") "cli"])-    -- Existential over list elements: gamma's first review is changes-requested.-    assertEqual-      ["requests/alpha", "requests/gamma"]-      (selected [FieldEquals (NestedField "reviews" "outcome") "approved"])-    -- The other nested shape: a record-valued key rather than a list of records.-    assertEqual-      ["notes/scratch", "requests/beta"]-      (selected [FieldEquals (NestedField "generated" "by") "human:nadeem"])-    assertEqual ["notes/scratch"] (selected [FieldAbsent (TopLevelField "status")])-    assertEqual ["requests/gamma"] (selected [FieldPresent (TopLevelField "completedAt")])-    -- A key no concept carries selects nothing, which is not an error.-    assertEqual [] (selected [FieldEquals (TopLevelField "status") "withdrawn"])-    -- Repeating a key is an "or".-    assertEqual-      ["requests/alpha", "requests/beta"]-      ( selected-          [ FieldEquals (TopLevelField "status") "accepted",-            FieldEquals (TopLevelField "status") "proposed"-          ]-      )-    -- Different keys are an "and".-    assertEqual-      ["requests/beta"]-      ( selected-          [ FieldEquals (TopLevelField "type") "Improvement Request",-            FieldEquals (TopLevelField "status") "proposed"-          ]-      )-    -- Grouping is by question as well as key, so these two are a conjunction of-    -- two groups and can never both hold.-    assertEqual-      []-      ( selected-          [ FieldEquals (TopLevelField "status") "accepted",-            FieldAbsent (TopLevelField "status")-          ]-      )---- | A profile checks the /question/, not the bundle: a filter naming a key the--- profile does not declare, or a value outside a closed vocabulary, can never--- select anything, and saying so is the whole reason @okf concepts@ takes a--- @--profile@.-testCheckFiltersAgainstProfile :: IO (Either Text ())-testCheckFiltersAgainstProfile = do-  descriptorPath <- fixtureFilePath "profiles/concept-filters.dhall"-  loaded <- loadProfileFile descriptorPath-  pure $ do-    spec <- first ("failed to load concept-filter profile: " <>) loaded-    compiled <- firstShow (compileProfile spec)-    openTypes <- firstShow (compileProfile (spec & #allowUnknownTypes .~ True))-    let checkAll = checkFiltersAgainstProfile compiled []-        checkFor wantedTypes = checkFiltersAgainstProfile compiled wantedTypes-        statusVocabulary = ["proposed", "accepted", "completed", "rejected"]-        reviewOutcomes = ["approved", "changes-requested", "commented"]-        typeNames = ["Improvement Request", "Note"]--    -- THE REGRESSION GUARD FOR THE ORDERING TRAP. 'status' is both an OKF v0.2-    -- core key ('coreFrontmatterFields' holds it) and a key this profile closes-    -- with four values. A refactor that asks "is this a core key?" before "does-    -- the profile declare it?" passes every other assertion in this test and-    -- silently waves the headline typo straight through.-    assertEqual-      [FilterValueNotInVocabulary (TopLevelField "status") "acepted" statusVocabulary]-      (checkAll [FieldEquals (TopLevelField "status") "acepted"])-    assertEqual [] (checkAll [FieldEquals (TopLevelField "status") "accepted"])--    -- A key no scope declares, whatever question is asked of it.-    assertEqual-      [FilterFieldNotDeclared (TopLevelField "statuz")]-      (checkAll [FieldEquals (TopLevelField "statuz") "x"])-    assertEqual-      [FilterFieldNotDeclared (TopLevelField "statuz")]-      (checkAll [FieldPresent (TopLevelField "statuz")])-    assertEqual-      [FilterFieldNotDeclared (TopLevelField "statuz")]-      (checkAll [FieldAbsent (TopLevelField "statuz")])-    assertEqual [] (checkAll [FieldPresent (TopLevelField "completedAt")])--    -- A nested member's vocabulary is reached through the parent's-    -- elementFields; a member declared without one accepts anything.-    assertEqual-      [FilterValueNotInVocabulary (NestedField "reviews" "outcome") "approvd" reviewOutcomes]-      (checkAll [FieldEquals (NestedField "reviews" "outcome") "approvd"])-    assertEqual [] (checkAll [FieldEquals (NestedField "reviews" "reviewer") "anyone"])-    assertEqual-      [FilterFieldNotDeclared (NestedField "reviews" "reviewr")]-      (checkAll [FieldEquals (NestedField "reviews" "reviewr") "anyone"])-    -- The other nested shape: objectFields on a record-valued key.-    assertEqual [] (checkAll [FieldEquals (NestedField "generated" "by") "human:nadeem"])--    -- The core-field fallback, for a key the profile never mentions: 'timestamp'-    -- is an OKF key, and okf owns the shape of 'verified' as well as its name.-    assertEqual [] (checkAll [FieldEquals (TopLevelField "timestamp") "2026-08-09T00:00:00Z"])-    assertEqual [] (checkAll [FieldEquals (NestedField "verified" "by") "human:nadeem"])--    -- 'type' has no allowedValues anywhere; its vocabulary is the profile's-    -- declared type names, and only while allowUnknownTypes is False.-    assertEqual-      [FilterValueNotInVocabulary (TopLevelField "type") "Ghost" typeNames]-      (checkAll [FieldEquals (TopLevelField "type") "Ghost"])-    assertEqual [] (checkAll [FieldEquals (TopLevelField "type") "Note"])-    assertEqual-      []-      (checkFiltersAgainstProfile openTypes [] [FieldEquals (TopLevelField "type") "Ghost"])--    -- THE REGRESSION GUARD FOR THE SCOPE TRAP. 'noteKind' is declared plainly-    -- profile-wide and closed on 'Note' alone. Treating the profile-wide rules-    -- as a scope of their own would see an empty allowed-value list there, read-    -- it as "unconstrained", and never report anything for this key at all.-    -- Asking about 'Note' specifically must report; asking about every type must-    -- not, because an 'Improvement Request' really may hold any value here.-    assertEqual-      [FilterValueNotInVocabulary (TopLevelField "noteKind") "bogus" ["scratch", "reference"]]-      (checkFor ["Note"] [FieldEquals (TopLevelField "noteKind") "bogus"])-    assertEqual [] (checkFor ["Note"] [FieldEquals (TopLevelField "noteKind") "scratch"])-    assertEqual [] (checkAll [FieldEquals (TopLevelField "noteKind") "bogus"])--    -- Restricting to the types the command line named is a real restriction:-    -- 'targetPlan' is declared only on 'Improvement Request'.-    assertEqual [] (checkAll [FieldPresent (TopLevelField "targetPlan")])-    assertEqual [] (checkFor ["Improvement Request"] [FieldPresent (TopLevelField "targetPlan")])-    assertEqual-      [FilterFieldNotDeclared (TopLevelField "targetPlan")]-      (checkFor ["Note"] [FieldPresent (TopLevelField "targetPlan")])--    -- Every error is reported, not only the first.-    assertEqual-      [ FilterValueNotInVocabulary (TopLevelField "status") "acepted" statusVocabulary,-        FilterFieldNotDeclared (TopLevelField "statuz")-      ]-      ( checkAll-          [ FieldEquals (TopLevelField "status") "acepted",-            FieldEquals (TopLevelField "statuz") "x"-          ]-      )--fixturePath :: FilePath -> IO FilePath-fixturePath name = do-  let candidates =-        [ "okf-core" </> "test" </> "fixtures" </> name,-          "test" </> "fixtures" </> name-        ]-  findExisting candidates-  where-    findExisting [] = fail ("fixture not found: " <> name)-    findExisting (candidate : rest) = do-      exists <- doesDirectoryExist candidate-      if exists then pure candidate else findExisting rest--requireConcept :: Text -> [Concept] -> Either Text Concept-requireConcept rawId concepts = do-  conceptId <- firstShow (parseConceptId rawId)-  case findConcept conceptId concepts of-    Just concept -> Right concept-    Nothing -> Left ("missing concept " <> rawId)--requireConceptIO :: Text -> [Concept] -> IO Concept-requireConceptIO rawId concepts =-  case requireConcept rawId concepts of-    Right concept -> pure concept-    Left message -> fail (Text.unpack message)--withFixtureBundle :: (FilePath -> IO (Either Text ())) -> IO (Either Text ())-withFixtureBundle action = do-  temporaryDirectory <- getTemporaryDirectory-  root <- createTempDirectory temporaryDirectory "okf-core-test"-  createFixtureBundle root-  result <- action root-  removeDirectoryRecursive root-  pure result--createFixtureBundle :: FilePath -> IO ()-createFixtureBundle root = do-  createDirectoryIfMissing True (root </> "datasets")-  createDirectoryIfMissing True (root </> "tables")-  Text.IO.writeFile (root </> "index.md") "# Reserved root index\n"-  Text.IO.writeFile (root </> "tables" </> "index.md") "# Reserved tables index\n"-  Text.IO.writeFile (root </> "tables" </> "log.md") "# Reserved log\n"-  Text.IO.writeFile-    (root </> "datasets" </> "sales.md")-    (fixtureDocument "Dataset" "Sales" "Sales dataset." "")-  Text.IO.writeFile-    (root </> "tables" </> "customers.md")-    (fixtureDocument "BigQuery Table" "Customers" "Customer records." "")-  Text.IO.writeFile-    (root </> "tables" </> "orders.md")-    ( fixtureDocument-        "BigQuery Table"-        "Orders"-        "Order records."-        ( Text.unlines-            [ "[Customers absolute](/tables/customers.md)",-              "[Customers relative](./customers.md)",-              "[Sales relative](../datasets/sales.md)",-              "[Broken](/missing.md)",-              "[External](https://example.com/x.md)"-            ]-        )-    )--fixtureDocument :: Text -> Text -> Text -> Text -> Text-fixtureDocument typeName titleText descriptionText documentBody =-  Text.unlines-    [ "---",-      "type: " <> typeName,-      "title: " <> titleText,-      "description: " <> descriptionText,-      "timestamp: 2026-06-16T00:00:00Z",-      "---",-      "",-      documentBody-    ]+import Control.Exception (AsyncException (UserInterrupt), bracket, throwIO, try)+import Data.Aeson (object, toJSON, (.=))+import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Foldable (for_, toList)+import Data.List qualified as List+import Data.Map.Strict (Map)+import Data.Map.Strict qualified as Map+import Data.Maybe (catMaybes, listToMaybe, mapMaybe, maybeToList)+import Data.Set qualified as Set+import Data.Text qualified as Text+import Data.Text.IO qualified as Text.IO+import Data.Time (fromGregorian)+import Dhall.Parser qualified as Dhall+import Okf.Actor+import Okf.Bundle+import Okf.ConceptId+import Okf.Discovery+import Okf.Document+import Okf.Exception (catchSynchronous)+import Okf.Graph+import Okf.Index+import Okf.Log+import Okf.Markdown+import Okf.Path++-- 'List' and 'Object' are 'Cardinality' constructors; aeson's same-named+-- 'Value' constructors are reached as 'Aeson.Object' and friends.+import Okf.Prelude hiding (List, Object, setField, (.=))++-- 'HumanActor' is both an 'Okf.Actor' constructor and a 'FieldFormat'+-- alternative. This module names the actor far more often, so the format is+-- reached as 'Profile.HumanActor'.+import Okf.Profile hiding (HumanActor)+import Okf.Profile qualified as Profile+import Okf.Profile.Bootstrap+import Okf.Profile.Discovery qualified as ProfileDiscovery+import Okf.Profile.Documentation+import Okf.Profile.Registry+import Okf.Profile.Sweep qualified as Sweep+import Okf.Query+import Okf.Trust+import Okf.Validation+import System.Directory+  ( createDirectoryIfMissing,+    createDirectoryLink,+    createFileLink,+    doesDirectoryExist,+    doesFileExist,+    getTemporaryDirectory,+    makeAbsolute,+    removeDirectoryRecursive,+  )+import System.Exit (exitFailure)+import System.FilePath (normalise, takeDirectory, (</>))+import System.IO.Temp (createTempDirectory)+import "generic-lens" Data.Generics.Labels ()++main :: IO ()+main = do+  results <-+    sequence+      [ testIO "synchronous catches preserve asynchronous cancellation" testCatchSynchronous,+        testIO "bootstrap descriptors round-trip from local sources and physical paths" testBootstrapRoundTrip,+        testIO "bootstrap expressions preserve hashes and reject relative imports" testBootstrapExpressions,+        test "bootstrap paths and versions" testBootstrapPure,+        test "parseActor classifies the three specification section 7 shapes" testParseActorShapes,+        test "renderActor inverts parseActor on every input" testActorRoundTrip,+        test "parse valid document with YAML frontmatter" testParseValidDocument,+        test "parse document with no frontmatter as empty-frontmatter body" testParseNoFrontmatter,+        test "reject unterminated frontmatter" testRejectUnterminatedFrontmatter,+        test "reject frontmatter that is not a YAML mapping" testRejectNonMappingFrontmatter,+        test "validate permissive profile with only type" testPermissiveValidation,+        test "validate strict profile requiring title description generated" testStrictValidation,+        test "strict validation accepts generated, falls back to timestamp, reports neither" testStrictValidationGeneratedFamily,+        test "validate rejects tags that are not a string list" testRejectInvalidTags,+        test "round-trip preserves semantic frontmatter and body" testRoundTrip,+        test "reject invalid concept id segment" testRejectInvalidConceptId,+        test "convert concept id tables/users to tables/users.md" testConceptIdToFilePath,+        testIO "walkBundle reports a structured IO error for a missing root" testWalkBundleMissingRoot,+        testIO "walkBundle skips index.md and log.md" testWalkBundleSkipsReserved,+        testIO "walkBundle discovers nested concept IDs" testWalkBundleDiscoversNestedConceptIds,+        testIO "walkBundleInventory sees a non-Markdown file that is not a concept" testWalkBundleInventorySeesNonMarkdown,+        testIO "discoverBundleRoots finds a directory holding index.md" testDiscoverIndexMd,+        testIO "discoverBundleRoots finds a directory holding a typed concept" testDiscoverTypedConcept,+        testIO "discoverBundleRoots ignores markdown without a type field" testDiscoverIgnoresPlainMarkdown,+        testIO "discoverBundleRoots does not descend into a bundle it found" testDiscoverPrunesNestedBundles,+        testIO "discoverBundleRoots skips hidden and build directories" testDiscoverSkipsNoise,+        testIO "discoverBundleRoots honours maxDepth" testDiscoverHonoursMaxDepth,+        testIO "discoverBundleRoots reports a fixture bundle as its own root" testDiscoverFixtureBundle,+        test "parseLog/serializeLog round-trips a canonical log" testLogRoundTrip,+        test "validateLog flags a non-ISO date heading" testValidateLogNonIsoDate,+        test "validateLog flags an empty date group" testValidateLogEmptyDay,+        test "validateLog flags out-of-order days" testValidateLogOutOfOrder,+        testIO "walkLogs discovers nested log.md files" testWalkLogsDiscoversNested,+        test "logStaleness flags a concept newer than its nearest log" testLogStalenessFlagsNewerConcept,+        test "logStaleness reads generated.at ahead of the legacy timestamp" testLogStalenessReadsGeneratedAt,+        test "logStaleness prefers the deepest enclosing log" testLogStalenessPrefersDeepestLog,+        test "appendLogEntry inserts newest-first and prepends within a day" testAppendLogEntry,+        test "log diffs expose removals and exact line endings" testLogDiff,+        testIO "generateIndex groups documents by frontmatter type" testGenerateIndexGroupsByType,+        testIO "index endings are exact for every directory shape" testIndexEndings,+        testIO "index writers preserve endings and versions across directory shapes" testIndexWriterEndings,+        testIO "extractLinks resolves relative and absolute bundle links" testExtractLinksResolveBundleLinks,+        testIO "extractLinks ignores external markdown URLs" testExtractLinksIgnoresExternalUrls,+        testIO "buildGraph includes only edges to existing concepts" testBuildGraphIncludesKnownEdges,+        testIO "writeBundleIndexes is deterministic" testWriteBundleIndexesDeterministic,+        testIO "readBundleVersion reads a declared, absent, or unparseable okf_version" testReadBundleVersion,+        testIO "readBundleVersion accepts the unquoted YAML number form" testReadBundleVersionUnquoted,+        testIO "writeBundleIndexes preserves an existing okf_version declaration" testWriteBundleIndexesPreservesVersion,+        testIO "writeBundleIndexesWith declares a version and leaves others alone" testWriteBundleIndexesDeclaresVersion,+        testIO "fixture valid bundle validates and graphs expected edges" testFixtureValidBundle,+        testIO "fixture v01 legacy bundle validates strictly through the fallback" testFixtureV01LegacyBundle,+        testIO "fixture graph JSON shape is stable" testFixtureGraphJsonShape,+        testIO "fixture unterminated frontmatter reports parse error" testFixtureUnterminatedFrontmatter,+        testIO "fixture missing type reports validation error" testFixtureMissingType,+        test "frontmatter builder round-trips through serialize and parse" testFrontmatterBuilderRoundTrip,+        test "serializeDocument emits deterministic key order" testSerializeDeterministicKeyOrder,+        test "serializeDocument orders generated before the superseded timestamp" testSerializeGeneratedBeforeTimestamp,+        test "strict validation joins footnote labels to sources ids in both directions" testFootnoteAttributionJoin,+        test "footnote attribution is skipped entirely when a document has no sources" testFootnoteAttributionSkippedWithoutSources,+        test "footnote parsing is enabled, so a definition is not paragraph text" testFootnotesEnabled,+        test "enabling footnotes leaves log parsing and link extraction unchanged" testFootnotesDoNotRegressLogsOrLinks,+        test "extractFootnoteLabels ignores footnote syntax inside code" testExtractFootnoteLabelsIgnoresCode,+        test "extractFootnoteLabels keeps labels the parser erases and never ordinals" testExtractFootnoteLabelsKeepsErasedLabels,+        test "computationBlocks accepts both spellings and bounds its section" testComputationBlocks,+        test "computationBlocks cannot see a block inside an uncited footnote definition" testComputationBlocksFootnoteHazard,+        test "rendered concept link round-trips through extractConceptLinks" testConceptLinkRoundTrip,+        test "over-escaping relative links do not resolve inside bundle" testRejectOverEscapingRelativeLink,+        test "classifyPathReference implements the specification section 6.2 grammar" testClassifyPathReference,+        test "resolvePathReference decides existence against a bundle inventory" testResolvePathReference,+        test "every versioned field name is a core frontmatter field" testVersionedFieldsAreCoreFields,+        test "versionGate applies specification section 12 best-effort reading" testVersionGate,+        test "declared v0.2 reports a legacy timestamp that an undeclared bundle tolerates" testLegacyFieldInDeclaredV2,+        test "an unreadable or unknown declaration is a strict lint, never a refusal" testVersionDeclarationLints,+        test "validateBundle reports a dangling reference" testValidateBundleDanglingReference,+        test "validateBundle accepts a bundle whose links all resolve" testValidateBundleAcceptsResolved,+        test "validateBundle reports a dangling frontmatter path under strict only" testValidateBundleDanglingFrontmatterPath,+        test "a dangling relative path names the bundle-relative spelling that resolves" testDanglingFrontmatterPathAlternative,+        test "duplicateConceptIds finds repeated ids" testDuplicateConceptIds,+        test "conceptFromDocument derives typed fields from frontmatter" testConceptFromDocumentDerivesFields,+        test "conceptGenerated projects the v0.2 generated family" testConceptGeneratedProjection,+        test "readGenerated ignores a generated mapping with no by actor" testReadGeneratedWithoutActor,+        test "readVerified reads a list and normalises a bare mapping to one element" testReadVerifiedShapes,+        test "setVerified always writes a list and round-trips" testVerifiedRoundTrip,+        test "readStatus defaults to stable and preserves an unknown value" testReadStatus,+        test "readStaleAfter reads the date verbatim" testReadStaleAfter,+        test "trustTier derives the three specification section 5.3 tiers" testTrustTier,+        test "latestVerification returns the newest at" testLatestVerification,+        test "staleness compares inclusively against a supplied day" testStaleness,+        test "readSources reads entries and skips one without resource" testReadSources,+        test "usage_window applies at document scope with per-entry override" testUsageWindowOverride,+        test "setSources and setUsageWindow round-trip through serialize and parse" testSourcesRoundTrip,+        test "strict validation reports sources missing resource and duplicate ids" testValidateSources,+        test "the attested computation contract reads from the specification worked example" testReadAttestedComputationContract,+        test "a malformed contract field is not read rather than rejected" testReadAttestedComputationDegenerateShapes,+        test "the specification worked example serializes byte-identically" testAttestedComputationRoundTrip,+        test "readComputationSources joins the body section to the computation key" testReadComputationSources,+        test "strict validation reports an Attested Computation with no runtime" testValidateAttestedComputationRuntime,+        testIO "writeBundle then walkBundle round-trips" testWriteBundleRoundTrip,+        testIO "fixture dangling link reports a bundle validation error" testFixtureDanglingLink,+        testIO "fixture dangling frontmatter path reports exactly one strict problem" testFixtureDanglingFrontmatterPath,+        testIO "fixture attested computation bundle reports one missing runtime and no path problem" testFixtureAttestedComputation,+        testIO "loadProfileFile decodes the postgresql fixture" testLoadProfileFixture,+        testIO "loadProfileFile decodes record-completed document ID rules" testLoadDocumentIdProfileFixture,+        testIO "loadProfileFile exposes nested reference and uniqueness declarations" testLoadNestedReferenceProfileFixture,+        testIO "sweep enumerates relaxations in declaration order" testSweepEnumeration,+        testIO "sweep applies each relaxation kind to the authored descriptor" testSweepApplyRelaxation,+        test "sweep reads expected.json in file order" testSweepExpectationOrder,+        testIO "sweep finds witnesses and unprotected relaxations on a two-case suite" testSweepWitnesses,+        testIO "sweep baseline reports a case that does not meet its expectation" testSweepBaselineFault,+        testIO "sweep classifies an open profile's relaxations by evidence and proof" testSweepClassification,+        testIO "sweep classifies closed-profile deletions as subsumed or acceptance-observable" testSweepClosedProfile,+        testIO "sweep reports an inert relaxation some case notices as a contradiction" testSweepContradiction,+        testIO "sweep applies manifest exceptions and reports stale ones" testSweepExceptions,+        test "sweep rejects malformed exception manifests" testSweepMalformedExceptions,+        testIO "behaviourKey erases only what validation never consults" testSweepBehaviourKeyErasures,+        testIO "loadProfileFile accepts the pre-type-frontmatter described schema" testLoadDescribedProfileFixture,+        testIO "loadProfileFile accepts the frozen EP-1 type-aware schema" testLoadTypeAwareCompatibilityFixture,+        testIO "loadProfileFile accepts the frozen EP-2 vocabulary schema" testLoadVocabularyCompatibilityFixture,+        testIO "loadProfileFile accepts the frozen EP-3 cardinality schema" testLoadCardinalityCompatibilityFixture,+        testIO "loadProfileFile accepts the frozen EP-4 format schema" testLoadFormatCompatibilityFixture,+        testIO "loadProfileFile decodes bounded nested review rules" testLoadNestedReviewsProfileFixture,+        testIO "loadProfileFile preserves the frozen bounded-nested schema" testLoadNestedCompatibilityFixture,+        testIO "loadProfileFile decodes same-scope conditions" testLoadConditionalFieldsProfileFixture,+        testIO "loadProfileFile preserves the frozen condition-aware schema" testLoadConditionalCompatibilityFixture,+        testIO "loadProfileFile preserves the frozen reference-aware schema" testLoadReferenceCompatibilityFixture,+        testIO "loadProfileFile preserves the complete 0.7.0.0 descriptor schema" testLoadPreNestedReferenceCompatibilityFixture,+        testIO "loadProfileFile and registry decoding preserve the complete 0.8.0.0 descriptor schema" testLoadPreGuidanceCompatibilityFixture,+        testIO "loadProfileFile and JSON preserve multiline guidance" testLoadGuidanceFixture,+        testIO "guidance does not affect profile validation" testGuidanceDoesNotAffectValidation,+        testIO "nested closure loads through current and frozen public decoders" testNestedClosureDecoding,+        test "nested closure validates records and merges policies" testNestedClosureValidation,+        test "nested closure scope, shape, condition and malformed-value matrix" testNestedClosureMatrix,+        testIO "product discovery constraints preserve scope, types and occurrence paths" testProductDiscoveryConstraints,+        testIO "every frozen generation fixture compiles, not merely decodes" testFrozenFixturesCompile,+        testIO "loadProfileFile preserves the frozen pre-bundle-version schema" testLoadPreBundleVersionCompatibilityFixture,+        testIO "loadProfileFile preserves the frozen pre-path schema" testLoadPrePathCompatibilityFixture,+        testIO "loadProfileFile preserves the frozen five-alternative format union" testLoadPreActorCompatibilityFixture,+        testIO "loadProfileFile preserves the frozen optional-presence schema" testLoadPreObjectCompatibilityFixture,+        testIO "loadProfileFile still accepts an okf 0.2.x descriptor" testLoadLegacyProfileFixture,+        testIO "profileFieldDescription finds required and recommended prose" testProfileFieldDescription,+        testIO "profileFieldDescription finds optional prose" testOptionalFieldDescription,+        testIO "profile JSON encoding emits type, not type_" testProfileJsonShape,+        test "field condition JSON encoding is stable" testFieldConditionJsonShape,+        test "handle reference JSON encoding is stable" testHandleReferenceJsonShape,+        test "field format JSON encoding is stable" testFieldFormatJsonShape,+        testIO "loadRegistry enumerates nested profiles and skips non-profiles" testRegistryEnumeratesProfiles,+        testIO "loadRegistry decodes every profile in the pinned catalogue snapshot" testPinnedCatalogueDecodes,+        testIO "loadRegistry reports a bare profile as a root entry" testRegistryRootProfile,+        testIO "resolveRegistryRef prefers package.dhall inside a directory" testResolveRegistryRef,+        testIO "loadRegistry reports a missing registry as Left" testRegistryLoadFailure,+        test "registry path intent is classified without mistaking remote URLs for paths" testLooksLikeRegistryPath,+        testIO "loadRegistryDetailed classifies actionable failures without rendered Dhall text" testRegistryDetailedFailures,+        testIO "profile discovery finds valid descriptors without pruning" testDiscoverProfileDescriptors,+        testIO "profile discovery excludes every non-descriptor fixture" testProfileDescriptorQualification,+        testIO "profile discovery treats a missing root as empty" testProfileDiscoveryMissingRoot,+        testIO "profile discovery skips symbolic links" testProfileDiscoverySkipsSymlink,+        testIO "profile discovery honours maxDepth" testProfileDiscoveryHonoursMaxDepth,+        testIO "profile discovery rejects remote text and bytes before I/O" testProfileDiscoveryRejectsRemote,+        test "profile source labels are compact and readable" testProfileSourceLabels,+        testIO "loadProfileSource attaches source provenance" testProfileSourceWrapper,+        testIO "DescriptorSource enumerates one basename export" testDescriptorSourceWrapper,+        testIO "DescriptorSource reports a non-profile as a source failure" testDescriptorSourceFailure,+        testIO "loadProfileSources merges registries in source order" testProfileSourcesMergeInOrder,+        testIO "loadProfileSources merges registry and descriptor sources in order" testMixedProfileSourcesMergeInOrder,+        testIO "loadProfileSources retains entries after a partial failure" testProfileSourcesPartialFailure,+        testIO "findSourcedProfiles exposes cross-source collisions" testProfileSourcesExposeCollisions,+        testIO "loadProfileSources drops exact duplicate references" testProfileSourcesDropDuplicates,+        test "parseDocumentId accepts only canonical handles" testParseDocumentId,+        testIO "documentIdsInBundle sorts handles by prefix and number" testDocumentIdsInBundle,+        test "nextDocumentId skips gaps and starts unused prefixes at one" testNextDocumentId,+        testIO "findConceptsByDocumentId resolves and reports duplicate handles" testFindConceptsByDocumentId,+        test "compileProfile rejects ambiguous definitions deterministically" testCompileProfileDefinitionErrors,+        test "compiled rules merge profile and type requirements" testCompiledProfileMerge,+        testIO "compiledProfileTypeNames preserves declaration order" testCompiledProfileTypeNames,+        testIO "compiledProfileRulesForType merges profile and type scope" testCompiledProfileRulesMergeTypeScope,+        testIO "compiled optional rules carry no presence clause" testCompiledProfileOptionalPresence,+        test "profileDocumentationSlug normalizes free-text type names" testProfileDocumentationSlug,+        test "duplicate type slugs are disambiguated positionally" testProfileDocumentationSlugCollisions,+        test "profile value display names match the documented vocabulary" testProfileValueDisplayNames,+        testIO "profile documentation renders a root concept" testProfileDocumentationRootConcept,+        test "profile documentation renders object rules" testProfileDocumentationObjectFields,+        testIO "profile documentation renders nested references and list uniqueness" testProfileDocumentationNestedReferenceAndUniqueness,+        test "profile documentation renders a required bundle version" testProfileDocumentationRequiredBundleVersion,+        testIO "profile documentation renders one concept per declared type" testProfileDocumentationTypeConcept,+        testIO "profile documentation renders inherited rules for a bare type" testProfileDocumentationInheritedRules,+        testIO "profile documentation renders effective guidance without frontmatter leakage" testProfileDocumentationGuidance,+        testIO "generated profile documentation round-trips through serialize and parse" testProfileDocumentationRoundTrip,+        testIO "generated profile documentation validates permissively and strictly" testProfileDocumentationValidates,+        testIO "generated profile documentation carries the default generated actor" testProfileDocumentationDefaultGenerated,+        testIO "generated profile documentation honours an explicit generated family" testProfileDocumentationExplicitGenerated,+        testIO "generated profile documentation omits generated on request" testProfileDocumentationOmittedGenerated,+        testIO "generated profile documentation has no dangling references" testProfileDocumentationLinksResolve,+        testIO "generated profile documentation is byte-stable across renders" testProfileDocumentationByteStable,+        testIO "generated profile documentation survives a filesystem round trip" testProfileDocumentationFilesystemRoundTrip,+        test "compiled vocabularies intersect in profile declaration order" testCompiledVocabularyIntersection,+        test "compileProfile rejects disjoint vocabularies" testUnsatisfiableVocabulary,+        test "compiled cardinality uses Any as identity and rejects contradictions" testCompiledCardinality,+        test "profile vocabularies validate strings, lists, and shapes" testVocabularyValidation,+        test "profile cardinality validates all JSON shapes and presence" testCardinalityValidation,+        test "cardinality suppresses redundant vocabulary shape errors" testCardinalityVocabularyInteraction,+        test "compiled formats refine Uri and reject contradictions" testCompiledFieldFormats,+        test "compileProfile rejects invalid format parameters" testInvalidFormatParameters,+        test "named formats validate parser boundaries, lists, and shapes" testNamedFormatValidation,+        test "the actor formats accept the three specification section 7 shapes" testActorFormatValidation,+        test "the numeric and boolean formats reject text and non-integers" testNonTextualFormatValidation,+        test "a non-textual format refines an unspecified cardinality to scalar" testNonTextualFormatRefinesCardinality,+        test "actor and integer narrow across scopes" testNewFormatsNarrowAcrossScopes,+        test "compiled nested rules merge and reject impossible outer cardinality" testCompiledNestedRules,+        test "nested record validation reports indexed paths and strict recommendations" testNestedRecordValidation,+        test "compileProfile rejects objectFields with an explicit scalar or list cardinality" testObjectFieldsRequireObjectShape,+        test "compileProfile refines an object rule to object cardinality" testCompileObjectRule,+        test "compileProfile normalizes a path rule at top-level and nested scope" testCompilePathRule,+        test "a type-scope path rule narrows the profile-scope one" testMergePathRule,+        test "compileProfile rejects incoherent path rules" testPathDefinitionErrors,+        test "compileProfile rejects an unreadable or unknown-major okfVersion" testProfileVersionParsing,+        test "compileProfile clamps a higher okfVersion minor to the supported one" testProfileVersionMinorClamp,+        test "compileProfile rejects an unreadable requireBundleVersion" testRequiredBundleVersionParsing,+        test "validateProfileVersion judges every declaration shape" testValidateProfileVersion,+        test "validateProfileVersion is inert without a requirement" testValidateProfileVersionUnrequired,+        test "compileProfile rejects a superseded field outside the optional list" testProfileVersionSupersededField,+        test "compileProfile rejects the actor formats in a v0.1 profile" testProfileVersionActorFormat,+        test "compileProfile does not judge a profile by its key names" testProfileVersionDoesNotJudgeKeyNames,+        test "validateProfile checks a top-level path-valued field" testValidatePathTopLevel,+        test "validateProfile checks sources[].resource with element indexes" testValidatePathNested,+        test "validateProfile checks a path inside an object-valued field" testValidatePathObjectScope,+        testIO "validateProfileWith resolves a non-Markdown path target" testValidateProfileWithInventory,+        testIO "the documented house profile reports the section 10 contract deviations" testAttestedComputationHouseProfile,+        test "compileProfile keeps a rule declaring both shapes at any cardinality" testCompileRecordOrListRule,+        test "validateProfile requires a member of an object field" testValidateObjectMember,+        test "validateProfile checks a bare mapping and a list against the same member rules" testValidateRecordOrList,+        test "validateProfile reports an object value where only a list is declared" testValidateObjectWrongShape,+        test "an object field with no member rules still requires a mapping" testValidateEmptyObjectRules,+        test "compileProfile rejects invalid same-scope field conditions" testConditionDefinitionErrors,+        test "top-level conditions gate presence without gating value checks" testTopLevelConditionalPresence,+        test "nested conditions use siblings and avoid cascading diagnostics" testNestedConditionalPresence,+        test "compileProfile rejects invalid document reference policies" testReferenceDefinitionErrors,+        test "document references resolve local handles and explicit external URIs" testDocumentReferenceValidation,+        testIO "compileProfile exposes nested references and record-list uniqueness" testCompileNestedReferenceAndUniqueness,+        testIO "nested references and record-list uniqueness validate in layers" testNestedReferenceAndUniquenessValidation,+        testIO "compileProfile rejects invalid nested reference and uniqueness declarations" testNestedReferenceAndUniquenessDefinitionErrors,+        test "optional fields are never missing but are fully value-checked" testOptionalFieldPresence,+        test "optional reference fields resolve handles when present" testOptionalReferenceValidation,+        test "optional nested fields are never missing inside records" testOptionalNestedFieldPresence,+        test "optional fields count as declared under closed field names" testOptionalFieldClosure,+        test "optional at one scope does not cancel the other scope's clause" testOptionalDoesNotCancelOtherScope,+        test "compileProfile rejects optional collisions and dead conditions" testOptionalDefinitionErrors,+        test "closed profiles reject unknown fields and isolate type fields" testClosedFieldValidation,+        test "profile rules apply to unknown concept types" testProfileRulesApplyToUnknownTypes,+        test "strict profile validation checks recommendations" testStrictProfileRecommendations,+        test "validateProfile accepts a conforming table concept" testProfileConformingTable,+        test "validateProfile flags a type not in the vocabulary" testProfileUnknownType,+        test "validateProfile flags a missing required field" testProfileMissingField,+        test "validateProfile flags a resource scheme mismatch" testProfileResourceMismatch,+        test "validateProfile flags a path pattern mismatch" testProfilePathMismatch,+        test "validateProfile flags a missing # Schema section" testProfileMissingSchema,+        test "validateProfile flags mismatched # Schema columns" testProfileSchemaColumnsMismatch,+        test "validateProfile accepts a conforming document ID" testProfileConformingDocumentId,+        test "validateProfile flags a missing document ID" testProfileMissingDocumentId,+        test "validateProfile flags malformed document IDs" testProfileMalformedDocumentIds,+        test "validateProfile flags duplicate document IDs" testProfileDuplicateDocumentIds,+        test "validateProfile document ID checks are off by default" testProfileDocumentIdsOffByDefault,+        test "schemaSectionColumns reads the header row of the Schema table" testSchemaSectionColumns,+        testIO "validateProfile reports the expected deviations for the fixture bundle" testProfileDeviationsFixture,+        testIO "validateProfile reports document ID fixture deviations" testDocumentIdDeviationsFixture,+        testIO "type-aware fixture is permissive but reports one strict recommendation" testTypeAwareProfileFixture,+        testIO "closed-field fixture reports missing and misspelled fields" testClosedFieldsFixture,+        testIO "cardinality fixture reports scalar and list mismatches" testCardinalityFixture,+        testIO "format fixture reports parser-backed mismatches" testFormatsFixture,+        testIO "nested review fixture validates records with indexed diagnostics" testNestedReviewsFixture,+        testIO "conditional fixture covers ADR, PostgreSQL, and review scopes" testConditionalFieldsFixture,+        testIO "document reference fixture covers local, external, self, and duplicate targets" testDocumentReferencesFixture,+        testIO "optional-field fixture reports only the recommendation and bad values" testOptionalFieldsFixture,+        test "parseFieldEquals and parseFieldSelector read the filter grammar" testParseConceptFilters,+        test "parseWhereCondition reads legacy, standalone, and expression conditions" testParseWhereConditions,+        test "scalarText compares numbers and booleans as JSON, containers as nothing" testQueryScalarText,+        testIO "filterConcepts selects over lists, nested records, presence, and absence" testFilterConceptsOverFixture,+        testIO "checkFiltersAgainstProfile rejects undeclared keys and out-of-vocabulary values" testCheckFiltersAgainstProfile,+        testIO "filterConceptsWhere selects with inclusion, exclusion, and composition" testFilterConceptsWhereOverFixture,+        test "matchesPredicate needs a comparable scalar for every value question" testMatchesPredicateEdgeCases,+        testIO "checkPredicateAgainstProfile checks every operand with legacy scope rules" testCheckPredicateAgainstProfile,+        test "compareNatural orders digit runs by value" testCompareNatural,+        test "parseSortKey reads keys and directions" testParseSortKey,+        testIO "sortConcepts orders by frontmatter keys" testSortConceptsOverFixture+      ]+  unless (and results) exitFailure++test :: Text -> Either Text () -> IO Bool+test name assertion =+  case assertion of+    Right () -> do+      putStrLn ("PASS " <> Text.unpack name)+      pure True+    Left message -> do+      putStrLn ("FAIL " <> Text.unpack name <> ": " <> Text.unpack message)+      pure False++testIO :: Text -> IO (Either Text ()) -> IO Bool+testIO name assertion = do+  result <- assertion+  test name result++testParseActorShapes :: Either Text ()+testParseActorShapes = do+  assertEqual (HumanActor "ahormati") (parseActor "human:ahormati")+  assertEqual (ProcessActor "finance-nightly") (parseActor "process:finance-nightly")+  assertEqual (ProducerActor "reference_agent" "gemini-2.5-pro") (parseActor "reference_agent/gemini-2.5-pro")+  assertEqual (UnclassifiedActor "something") (parseActor "something")+  -- Section 7 writes the prefixes in lower case and section 5.3 makes the+  -- `human:` test load-bearing, so matching is case-sensitive.+  assertEqual (UnclassifiedActor "Human:ahormati") (parseActor "Human:ahormati")+  assertBool "human actor is human" (isHumanActor (parseActor "human:ahormati"))+  assertBool "producer actor is not human" (not (isHumanActor (parseActor "reference_agent/gemini-2.5-pro")))++testActorRoundTrip :: Either Text ()+testActorRoundTrip =+  for_+    [ "human:ahormati",+      "process:finance-nightly",+      "reference_agent/gemini-2.5-pro",+      "something",+      "Human:ahormati",+      "human:",+      "/version",+      "producer/",+      "a/b/c",+      ""+    ]+    (\raw -> assertEqual raw (renderActor (parseActor raw)))++testParseValidDocument :: Either Text ()+testParseValidDocument = do+  document <- firstShow (parseDocument sampleDocument)+  assertEqual (Just (String "BigQuery Table")) (frontmatterLookup "type" (document ^. #frontmatter))+  assertEqual "# Schema\n\nBody text.\n" (body document)++testParseNoFrontmatter :: Either Text ()+testParseNoFrontmatter = do+  document <- firstShow (parseDocument "# Draft\n")+  assertEqual Nothing (frontmatterLookup "type" (document ^. #frontmatter))+  assertEqual "# Draft\n" (body document)++testRejectUnterminatedFrontmatter :: Either Text ()+testRejectUnterminatedFrontmatter =+  assertEqual (Left UnterminatedFrontmatter) (parseDocument "---\ntype: BigQuery Table\n")++testRejectNonMappingFrontmatter :: Either Text ()+testRejectNonMappingFrontmatter =+  assertEqual (Left FrontmatterNotMapping) (parseDocument "---\n- one\n- two\n---\nBody\n")++testPermissiveValidation :: Either Text ()+testPermissiveValidation = do+  document <- firstShow (parseDocument "---\ntype: BigQuery Table\n---\nBody\n")+  assertEqual [] (validateDocument PermissiveConformance document)++testStrictValidation :: Either Text ()+testStrictValidation = do+  document <- firstShow (parseDocument "---\ntype: BigQuery Table\n---\nBody\n")+  let errors = validateDocument StrictAuthoring document+  assertBool "missing title" (MissingRecommendedField "title" `List.elem` errors)+  assertBool "missing description" (MissingRecommendedField "description" `List.elem` errors)+  assertBool "missing generated" (MissingGeneratedField `List.elem` errors)++-- | Specification section 5.2 satisfies the "when was this last changed"+-- requirement with `generated`, and section 13.1 permits falling back to the+-- superseded v0.1 `timestamp`. Both must pass strict validation; neither+-- present must fail it, naming the v0.2 field.+testStrictValidationGeneratedFamily :: Either Text ()+testStrictValidationGeneratedFamily = do+  let strictErrors source = validateDocument StrictAuthoring <$> firstShow (parseDocument source)+      preamble = "---\ntype: BigQuery Table\ntitle: Orders\ndescription: Order fact table.\n"+  withGenerated <- strictErrors (preamble <> "generated: { by: human:ahormati, at: 2026-06-20T22:53:05Z }\n---\nBody\n")+  assertEqual [] withGenerated+  withLegacyTimestamp <- strictErrors (preamble <> "timestamp: 2026-06-16T00:00:00Z\n---\nBody\n")+  assertEqual [] withLegacyTimestamp+  withNeither <- strictErrors (preamble <> "---\nBody\n")+  assertEqual [MissingGeneratedField] withNeither+  -- `generated` present but without the actor section 5.2 requires within it.+  withoutActor <- strictErrors (preamble <> "generated: { at: 2026-06-20T22:53:05Z }\n---\nBody\n")+  assertEqual [GeneratedMustHaveActor] withoutActor+  -- Section 11 forbids rejecting a bundle for a missing optional field, so+  -- neither diagnostic may fire under PermissiveConformance.+  permissive <- validateDocument PermissiveConformance <$> firstShow (parseDocument (preamble <> "---\nBody\n"))+  assertEqual [] permissive++testRejectInvalidTags :: Either Text ()+testRejectInvalidTags = do+  document <- firstShow (parseDocument "---\ntype: BigQuery Table\ntags: orders\n---\nBody\n")+  assertEqual [FieldMustBeListOfText "tags"] (validateDocument PermissiveConformance document)++testRoundTrip :: Either Text ()+testRoundTrip = do+  document <- firstShow (parseDocument sampleDocument)+  assertEqual [] (validateDocument PermissiveConformance document)+  assertEqual [] (validateDocument StrictAuthoring document)+  reparsed <- firstShow (parseDocument (serializeDocument document))+  assertEqual (document ^. #frontmatter) (reparsed ^. #frontmatter)+  assertEqual (body document) (body reparsed)++testRejectInvalidConceptId :: Either Text ()+testRejectInvalidConceptId =+  assertEqual (Left (InvalidConceptIdSegment "-users")) (parseConceptId "tables/-users")++testConceptIdToFilePath :: Either Text ()+testConceptIdToFilePath = do+  conceptId <- firstShow (parseConceptId "tables/users")+  assertEqual "tables/users.md" (conceptIdToFilePath conceptId)++testWalkBundleMissingRoot :: IO (Either Text ())+testWalkBundleMissingRoot = do+  temporaryDirectory <- getTemporaryDirectory+  root <- createTempDirectory temporaryDirectory "okf-core-missing-parent"+  let missingRoot = root </> "missing"+  result <- walkBundle missingRoot+  removeDirectoryRecursive root+  pure+    ( case result of+        Left (BundleIoError path message)+          | path == missingRoot && "does not exist" `Text.isInfixOf` message -> Right ()+        other -> Left ("expected missing-root BundleIoError, got " <> Text.pack (show other))+    )++testWalkBundleSkipsReserved :: IO (Either Text ())+testWalkBundleSkipsReserved =+  withFixtureBundle+    ( \root -> do+        concepts <- readBundle root+        pure (assertEqual ["datasets/sales", "tables/customers", "tables/orders"] (renderConceptId . conceptIdOf <$> concepts))+    )++-- | The gap this milestone closes: @references\/attesters\/revenue.py@ is+-- specification §6.3's own example of what an @attester.resource@ points at, and+-- before 'walkBundleInventory' existed nothing in okf could tell whether it was+-- there. It must be visible to the inventory without becoming a concept, since+-- only a @.md@ file carries frontmatter to validate.+testWalkBundleInventorySeesNonMarkdown :: IO (Either Text ())+testWalkBundleInventorySeesNonMarkdown = do+  temporaryDirectory <- getTemporaryDirectory+  root <- createTempDirectory temporaryDirectory "okf-core-inventory"+  createFixtureBundle root+  createDirectoryIfMissing True (root </> "references" </> "attesters")+  Text.IO.writeFile (root </> "references" </> "attesters" </> "revenue.py") "print('receipt')\n"+  concepts <- readBundle root+  walked <- walkBundleInventory root+  removeDirectoryRecursive root+  pure+    ( do+        inventory <- firstShow walked+        assertBool+          "the .py file is in the inventory"+          (bundleInventoryMember "references/attesters/revenue.py" inventory)+        assertBool+          "the .py file is not a concept"+          (notElem "references/attesters/revenue" (renderConceptId . conceptIdOf <$> concepts))+        assertBool+          "a concept's own file is in the inventory"+          (bundleInventoryMember "tables/orders.md" inventory)+        -- A reserved file is not a concept but is still a file, so a path naming+        -- one names something that exists.+        assertBool "a reserved file is in the inventory" (bundleInventoryMember "index.md" inventory)+        assertBool+          "a file that is not there is not in the inventory"+          (not (bundleInventoryMember "references/attesters/gone.py" inventory))+        -- An in-memory bundle knows its own concepts and honestly cannot know+        -- anything else.+        let inMemory = bundleInventoryOfConcepts concepts+        assertBool+          "the in-memory inventory holds concept paths"+          (bundleInventoryMember "tables/orders.md" inMemory)+        assertBool+          "the in-memory inventory cannot know a non-Markdown file"+          (not (bundleInventoryMember "references/attesters/revenue.py" inMemory))+    )++testWalkBundleDiscoversNestedConceptIds :: IO (Either Text ())+testWalkBundleDiscoversNestedConceptIds =+  withFixtureBundle+    ( \root -> do+        concepts <- readBundle root+        pure+          ( do+              expected <- firstShow (parseConceptId "tables/orders")+              assertBool "nested concept exists" (isJust (findConcept expected concepts))+          )+    )++-- | Build a throwaway directory tree, run an action on it, and clean up.+withDiscoveryTree :: String -> [(FilePath, Text)] -> (FilePath -> IO a) -> IO a+withDiscoveryTree label files action = do+  temporaryDirectory <- getTemporaryDirectory+  root <- createTempDirectory temporaryDirectory label+  for_ files $ \(relativePath, content) -> do+    createDirectoryIfMissing True (root </> takeDirectory relativePath)+    Text.IO.writeFile (root </> relativePath) content+  result <- action root+  removeDirectoryRecursive root+  pure result++typedConcept :: Text -> Text+typedConcept titleText =+  Text.unlines ["---", "type: Table", "title: " <> titleText, "---", "", "# " <> titleText]++plainMarkdown :: Text+plainMarkdown = "# Just prose\n\nNo frontmatter here.\n"++testDiscoverIndexMd :: IO (Either Text ())+testDiscoverIndexMd =+  withDiscoveryTree "okf-discovery-index" [("kb/index.md", "# Index\n")] $ \root -> do+    found <- discoverBundleRoots defaultDiscoveryOptions root+    pure (assertEqual [normalise (root </> "kb")] found)++testDiscoverTypedConcept :: IO (Either Text ())+testDiscoverTypedConcept =+  withDiscoveryTree "okf-discovery-typed" [("kb/tables/orders.md", typedConcept "Orders")] $ \root -> do+    found <- discoverBundleRoots defaultDiscoveryOptions root+    pure (assertEqual [normalise (root </> "kb" </> "tables")] found)++testDiscoverIgnoresPlainMarkdown :: IO (Either Text ())+testDiscoverIgnoresPlainMarkdown =+  withDiscoveryTree+    "okf-discovery-plain"+    [("notes/README.md", plainMarkdown), ("notes/CHANGELOG.md", plainMarkdown)]+    $ \root -> do+      found <- discoverBundleRoots defaultDiscoveryOptions root+      pure (assertEqual [] found)++testDiscoverPrunesNestedBundles :: IO (Either Text ())+testDiscoverPrunesNestedBundles =+  withDiscoveryTree+    "okf-discovery-prune"+    [ ("kb/index.md", "# Index\n"),+      ("kb/tables/index.md", "# Tables\n"),+      ("kb/tables/orders.md", typedConcept "Orders")+    ]+    $ \root -> do+      found <- discoverBundleRoots defaultDiscoveryOptions root+      pure (assertEqual [normalise (root </> "kb")] found)++testDiscoverSkipsNoise :: IO (Either Text ())+testDiscoverSkipsNoise =+  withDiscoveryTree+    "okf-discovery-noise"+    [ (".hidden/index.md", "# Hidden\n"),+      ("dist-newstyle/index.md", "# Build output\n"),+      ("kb/index.md", "# Index\n")+    ]+    $ \root -> do+      found <- discoverBundleRoots defaultDiscoveryOptions root+      pure (assertEqual [normalise (root </> "kb")] found)++testDiscoverHonoursMaxDepth :: IO (Either Text ())+testDiscoverHonoursMaxDepth =+  withDiscoveryTree "okf-discovery-depth" [("a/b/c/index.md", "# Deep\n")] $ \root -> do+    shallow <- discoverBundleRoots defaultDiscoveryOptions {maxDepth = 2} root+    deep <- discoverBundleRoots defaultDiscoveryOptions {maxDepth = 3} root+    pure (assertEqual [] shallow >> assertEqual [normalise (root </> "a" </> "b" </> "c")] deep)++testDiscoverFixtureBundle :: IO (Either Text ())+testDiscoverFixtureBundle = do+  bundle <- fixturePath "valid-bundle"+  found <- discoverBundleRoots defaultDiscoveryOptions bundle+  pure (assertEqual [normalise bundle] found)++testLogRoundTrip :: Either Text ()+testLogRoundTrip = do+  let canonicalLog =+        Text.unlines+          [ "# Directory Update Log",+            "",+            "## 2026-06-23",+            "* **Update**: Refreshed [orders](tables/orders.md).",+            "* **Creation**: Added customers.",+            "",+            "## 2026-06-01",+            "* Deprecated a stale note."+          ]+      parsed = parseLog canonicalLog+      reparsed = parseLog (serializeLog parsed)+  assertEqual+    ( Log+        { logTitle = "Directory Update Log",+          logDays =+            [ LogDay+                { logDate = "2026-06-23",+                  logEntries =+                    [ LogEntry (Just "Update") "Refreshed [orders](tables/orders.md).",+                      LogEntry (Just "Creation") "Added customers."+                    ]+                },+              LogDay+                { logDate = "2026-06-01",+                  logEntries = [LogEntry Nothing "Deprecated a stale note."]+                }+            ]+        }+    )+    parsed+  assertEqual parsed reparsed++testValidateLogNonIsoDate :: Either Text ()+testValidateLogNonIsoDate =+  assertBool+    "expected LogDateNotIso"+    (LogDateNotIso "not-a-date" `List.elem` validateLog (parseLog "# Log\n\n## not-a-date\n* **Update**: oops\n"))++testValidateLogEmptyDay :: Either Text ()+testValidateLogEmptyDay =+  assertBool+    "expected LogEmptyDay"+    (LogEmptyDay "2026-06-23" `List.elem` validateLog (parseLog "# Log\n\n## 2026-06-23\n"))++testValidateLogOutOfOrder :: Either Text ()+testValidateLogOutOfOrder =+  assertBool+    "expected LogDaysOutOfOrder"+    ( LogDaysOutOfOrder "2026-01-01" "2026-06-23"+        `List.elem` validateLog (parseLog "# Log\n\n## 2026-01-01\n* Old.\n\n## 2026-06-23\n* New.\n")+    )++testWalkLogsDiscoversNested :: IO (Either Text ())+testWalkLogsDiscoversNested = do+  temporaryDirectory <- getTemporaryDirectory+  root <- createTempDirectory temporaryDirectory "okf-core-logs"+  createDirectoryIfMissing True (root </> "tables")+  Text.IO.writeFile (root </> "log.md") "# Root Log\n\n## 2026-06-23\n* Root entry.\n"+  Text.IO.writeFile (root </> "tables" </> "log.md") "# Tables Log\n\n## 2026-06-22\n* Tables entry.\n"+  result <- walkLogs root+  removeDirectoryRecursive root+  pure+    ( case result of+        Right logs -> assertEqual ["log.md", "tables/log.md"] (logSourcePath <$> logs)+        Left bundleError -> Left ("expected logs, got " <> Text.pack (show bundleError))+    )++testLogStalenessFlagsNewerConcept :: Either Text ()+testLogStalenessFlagsNewerConcept = do+  staleId <- parseTestConceptId "stale"+  staleConcept <- testConceptWithTimestamp "stale" "2026-06-23T00:00:00Z"+  currentConcept <- testConceptWithTimestamp "current" "2026-01-01T00:00:00Z"+  let logs = [LogFile "log.md" (parseLog "# Log\n\n## 2026-06-01\n* **Update**: logged.\n")]+  assertEqual+    [ LogStaleness+        { staleConcept = staleId,+          staleConceptDate = "2026-06-23",+          staleLogPath = Just "log.md",+          staleLogDate = Just "2026-06-01"+        }+    ]+    (logStaleness [staleConcept, currentConcept] logs)++-- | Staleness reads the v0.2 `generated.at` (specification section 5.2), and+-- prefers it over the legacy `timestamp` it supersedes when both are present.+testLogStalenessReadsGeneratedAt :: Either Text ()+testLogStalenessReadsGeneratedAt = do+  generatedOnlyId <- parseTestConceptId "generated-only"+  bothId <- parseTestConceptId "both"+  generatedOnly <-+    testConceptWithFrontmatter+      "generated-only"+      "type: Test\ngenerated: { by: human:ahormati, at: 2026-06-23T00:00:00Z }\n"+  -- `generated.at` wins over `timestamp`: the stale date must be the June 24+  -- from `generated`, not the January 1 from the legacy key.+  bothKeys <-+    testConceptWithFrontmatter+      "both"+      "type: Test\ngenerated: { by: human:ahormati, at: 2026-06-24T00:00:00Z }\ntimestamp: 2026-01-01T00:00:00Z\n"+  let logs = [LogFile "log.md" (parseLog "# Log\n\n## 2026-06-01\n* **Update**: logged.\n")]+  assertEqual+    [ LogStaleness bothId "2026-06-24" (Just "log.md") (Just "2026-06-01"),+      LogStaleness generatedOnlyId "2026-06-23" (Just "log.md") (Just "2026-06-01")+    ]+    (logStaleness [bothKeys, generatedOnly] logs)++testLogStalenessPrefersDeepestLog :: Either Text ()+testLogStalenessPrefersDeepestLog = do+  usersId <- parseTestConceptId "tables/users"+  usersConcept <- testConceptWithTimestamp "tables/users" "2026-06-21T00:00:00Z"+  let logs =+        [ LogFile "log.md" (parseLog "# Root Log\n\n## 2026-06-01\n* **Update**: root.\n"),+          LogFile "tables/log.md" (parseLog "# Tables Log\n\n## 2026-06-20\n* **Update**: tables.\n")+        ]+  assertEqual+    [ LogStaleness+        { staleConcept = usersId,+          staleConceptDate = "2026-06-21",+          staleLogPath = Just "tables/log.md",+          staleLogDate = Just "2026-06-20"+        }+    ]+    (logStaleness [usersConcept] logs)++testLogDiff :: Either Text ()+testLogDiff =+  if and+    [ renderLogDiff "log.md" (Just "# Log\n\nAdoption evidence.\n- Old entry\n") "# Log\n\n- New entry\n"+        == "--- log.md\n+++ log.md\n@@ -1,4 +1,3 @@\n # Log\n \n-Adoption evidence.\n-- Old entry\n+- New entry\n",+      renderLogDiff "log.md" Nothing "# Log\n"+        == "--- /dev/null\n+++ log.md\n@@ -0,0 +1,1 @@\n+# Log\n",+      renderLogDiff "log.md" (Just "# Log\r\nold") "# Log\r\nnew\n"+        == "--- log.md\n+++ log.md\n@@ -1,2 +1,2 @@\n # Log\r\n-old\n\\ No newline at end of file\n+new\n",+      renderLogDiff "log.md" (Just "# Log\n") "# Log\r\n"+        == "--- log.md\n+++ log.md\n@@ -1,1 +1,1 @@\n-# Log\n+# Log\r\n",+      renderLogDiff "log.md" (Just "same\n") "same\n" == "--- log.md\n+++ log.md\n",+      renderLogDiff "a\t\"b/log.md" Nothing "new" == "--- /dev/null\n+++ \"a\\011\\\"b/log.md\"\n@@ -0,0 +1,1 @@\n+new\n\\ No newline at end of file\n"+    ]+    then Right ()+    else Left "log diff omitted a change or rendered an incorrect hunk"++testAppendLogEntry :: Either Text ()+testAppendLogEntry =+  assertEqual+    ( Log+        { logTitle = "Log",+          logDays =+            [ LogDay "2026-06-23" [LogEntry (Just "Update") "new"],+              LogDay "2026-06-01" [LogEntry (Just "Update") "prepended", LogEntry (Just "Creation") "old"]+            ]+        }+    )+    ( appendLogEntry+        "2026-06-01"+        (LogEntry (Just "Update") "prepended")+        ( appendLogEntry+            "2026-06-23"+            (LogEntry (Just "Update") "new")+            (Log "Log" [LogDay "2026-06-01" [LogEntry (Just "Creation") "old"]])+        )+    )++testGenerateIndexGroupsByType :: IO (Either Text ())+testGenerateIndexGroupsByType =+  withFixtureBundle+    ( \root -> do+        concepts <- readBundle root+        pure+          ( do+              orders <- requireConcept "tables/orders" concepts+              customers <- requireConcept "tables/customers" concepts+              let rendered = renderIndex [] [] [orders, customers]+              assertBool "has type heading" ("# BigQuery Table" `Text.isInfixOf` rendered)+              assertBool "has orders bullet" ("[Orders](orders.md) - Order records." `Text.isInfixOf` rendered)+              assertBool "has customers bullet" ("[Customers](customers.md) - Customer records." `Text.isInfixOf` rendered)+              -- §8's progressive disclosure reaches a file with no frontmatter:+              -- a directory holding only an attester used to render one newline.+              let withFiles = renderIndex [] ["revenue.py"] []+              assertEqual "# Files\n\n- [revenue.py](revenue.py)\n" withFiles+          )+    )++-- Exact bytes protect ordering, links and section spacing as well as EOF.+indexEndingCases :: [([FilePath], [FilePath], [FilePath], Text)]+indexEndingCases =+  [ ([], [], [], ""),+    (["z", "a"], [], [], directories),+    ([], ["z.py", "a.py"], [], files),+    ([], [], ["z", "b", "a"], concepts),+    (["z", "a"], ["z.py", "a.py"], ["z", "b", "a"], directories <> "\n" <> files <> "\n" <> concepts)+  ]+  where+    directories = "# Subdirectories\n\n- [a/](a/index.md)\n- [z/](z/index.md)\n"+    files = "# Files\n\n- [a.py](a.py)\n- [z.py](z.py)\n"+    concepts = "# Alpha\n\n- [Title a](a.md) - Description a.\n- [Title b](b.md) - Description b.\n\n# Zeta\n\n- [Title z](z.md) - Description z.\n"++indexEndingConcept :: FilePath -> Text+indexEndingConcept name =+  Text.unlines+    [ "---",+      "type: " <> (if name == "z" then "Zeta" else "Alpha"),+      "title: Title " <> Text.pack name,+      "description: Description " <> Text.pack name <> ".",+      "---",+      "Body."+    ]++testIndexEndings :: IO (Either Text ())+testIndexEndings = pure $ for_ indexEndingCases $ \(directories, files, names, expected) -> do+  concepts <- for names $ \name -> do+    cid <- firstShow (parseConceptId (Text.pack name))+    document <- firstShow (parseDocument (indexEndingConcept name))+    pure (conceptFromDocument cid document)+  assertEqual expected (renderIndex directories files concepts)+  assertEqual expected (renderRootIndex Nothing directories files concepts)+  assertEqual+    ("---\nokf_version: \"0.2\"\n---\n" <> (if Text.null expected then "" else "\n" <> expected))+    (renderRootIndex (Just (OkfVersion 0 2)) directories files concepts)++testIndexWriterEndings :: IO (Either Text ())+testIndexWriterEndings = do+  rootResults <- for indexEndingCases $ \(directories, files, names, expected) ->+    withDiscoveryTree "okf-root-index-endings" [] $ \root -> do+      for_ directories $ \directory -> createDirectoryIfMissing True (root </> directory)+      for_ files $ \file -> Text.IO.writeFile (root </> file) "content\n"+      for_ names $ \name -> Text.IO.writeFile (root </> name <> ".md") (indexEndingConcept name)+      variants <- for [Nothing, Just (OkfVersion 0 2)] $ \version -> do+        written <- writeBundleIndexesWith version root+        firstBytes <- renderBundleIndexes root+        firstRoot <- Text.IO.readFile (root </> "index.md")+        rewritten <- writeBundleIndexes root+        secondBytes <- renderBundleIndexes root+        secondRoot <- Text.IO.readFile (root </> "index.md")+        pure $ do+          firstShow written+          firstShow rewritten+          void (firstShow firstBytes)+          assertEqual firstBytes secondBytes+          assertEqual firstRoot secondRoot+          assertEqual+            ( case version of+                Nothing -> expected+                Just _ -> "---\nokf_version: \"0.2\"\n---\n" <> (if Text.null expected then "" else "\n" <> expected)+            )+            firstRoot+      pure (sequence_ variants)+  results <- for indexEndingCases $ \(directories, files, names, expected) ->+    withDiscoveryTree "okf-index-endings" [] $ \root -> do+      -- Exercise each shape both at the root and nested; child indexes start empty.+      for_ ["", "nested"] $ \prefix -> do+        createDirectoryIfMissing True (root </> prefix)+        for_ directories $ \directory -> createDirectoryIfMissing True (root </> prefix </> directory)+        for_ files $ \file -> Text.IO.writeFile (root </> prefix </> file) "content\n"+        for_ names $ \name -> Text.IO.writeFile (root </> prefix </> name <> ".md") (indexEndingConcept name)+      let readIndexes = do+            rendered <- renderBundleIndexes root+            case rendered of+              Left err -> pure (Left (Text.pack (show err)))+              Right indexes -> Right <$> traverse (\(path, _) -> (path,) <$> Text.IO.readFile (root </> path)) indexes+          rootBody =+            renderRootIndex Nothing ("nested" : directories) files+              <$> traverse+                (\name -> conceptFromDocument <$> firstShow (parseConceptId (Text.pack name)) <*> firstShow (parseDocument (indexEndingConcept name)))+                names+      firstWrite <- writeBundleIndexes root+      firstBytes <- readIndexes+      secondWrite <- writeBundleIndexes root+      secondBytes <- readIndexes+      -- Preserve a raw, unparseable declaration, then override it explicitly.+      Text.IO.writeFile (root </> "index.md") "---\nokf_version: \"future version\"\n---\n"+      preservedWrite <- writeBundleIndexes root+      preserved <- Text.IO.readFile (root </> "index.md")+      overrideWrite <- writeBundleIndexesWith (Just (OkfVersion 0 2)) root+      overridden <- Text.IO.readFile (root </> "index.md")+      pure $ do+        for_ [firstWrite, secondWrite, preservedWrite, overrideWrite] firstShow+        bytes <- firstBytes+        assertEqual firstBytes secondBytes+        expectedRoot <- rootBody+        assertEqual (Just expectedRoot) (lookup "index.md" bytes)+        assertEqual (Just expected) (lookup ("nested" </> "index.md") bytes)+        for_ [prefix </> directory </> "index.md" | prefix <- ["", "nested"], directory <- directories] $ \path ->+          assertEqual (Just "") (lookup path bytes)+        assertEqual ("---\nokf_version: \"future version\"\n---\n\n" <> expectedRoot) preserved+        assertEqual ("---\nokf_version: \"0.2\"\n---\n\n" <> expectedRoot) overridden+  pure (sequence_ (rootResults <> results))++testExtractLinksResolveBundleLinks :: IO (Either Text ())+testExtractLinksResolveBundleLinks =+  withFixtureBundle+    ( \root -> do+        concepts <- readBundle root+        pure+          ( do+              orders <- requireConcept "tables/orders" concepts+              customers <- firstShow (parseConceptId "tables/customers")+              sales <- firstShow (parseConceptId "datasets/sales")+              let links = extractConceptLinks orders+              assertBool "absolute or ./ customers link" (customers `List.elem` links)+              assertBool "../ sales link" (sales `List.elem` links)+          )+    )++testExtractLinksIgnoresExternalUrls :: IO (Either Text ())+testExtractLinksIgnoresExternalUrls =+  withFixtureBundle+    ( \root -> do+        concepts <- readBundle root+        pure+          ( do+              orders <- requireConcept "tables/orders" concepts+              assertEqual 4 (length (extractConceptLinks orders))+          )+    )++testBuildGraphIncludesKnownEdges :: IO (Either Text ())+testBuildGraphIncludesKnownEdges =+  withFixtureBundle+    ( \root -> do+        concepts <- readBundle root+        pure+          ( do+              orders <- firstShow (parseConceptId "tables/orders")+              customers <- firstShow (parseConceptId "tables/customers")+              missing <- firstShow (parseConceptId "missing")+              let graph = buildGraph concepts+              assertEqual 3 (length (nodes graph))+              assertBool "known edge exists" (Edge {source = orders, target = customers} `List.elem` edges graph)+              assertBool "broken edge excluded" (Edge {source = orders, target = missing} `notElem` edges graph)+          )+    )++testWriteBundleIndexesDeterministic :: IO (Either Text ())+testWriteBundleIndexesDeterministic =+  withFixtureBundle+    ( \root -> do+        firstResult <- writeBundleIndexes root+        firstIndex <- Text.IO.readFile (root </> "tables" </> "index.md")+        secondResult <- writeBundleIndexes root+        secondIndex <- Text.IO.readFile (root </> "tables" </> "index.md")+        pure+          ( do+              firstShow firstResult+              firstShow secondResult+              assertEqual firstIndex secondIndex+              assertBool "tables index has BigQuery Table section" ("# BigQuery Table" `Text.isInfixOf` secondIndex)+          )+    )++-- | Specification §12 permits a bundle-root @index.md@ to declare the version+-- it targets. Every shape of that declaration is readable and none is fatal.+testReadBundleVersion :: IO (Either Text ())+testReadBundleVersion = do+  declared <- versionOf [("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Root\n")]+  noKey <- versionOf [("index.md", "---\ntitle: Root\n---\n\n# Root\n")]+  noFrontmatter <- versionOf [("index.md", "# Root\n")]+  noIndex <- versionOf [("kb.md", "# Not an index\n")]+  unparseable <- versionOf [("index.md", "---\nokf_version: \"zero point two\"\n---\n\n# Root\n")]+  malformed <- versionOf [("index.md", "---\nokf_version: \"0.2\"\n\n# Root\n")]+  pure $ do+    assertEqual (Right (VersionDeclared (OkfVersion 0 2))) declared+    assertEqual (Right VersionUndeclared) noKey+    assertEqual (Right VersionUndeclared) noFrontmatter+    assertEqual (Right VersionUndeclared) noIndex+    assertEqual (Right (VersionUnparseable "zero point two")) unparseable+    assertEqual (Right VersionUndeclared) malformed++-- | A careless author writes @okf_version: 0.2@ without quotes, which YAML+-- reads as a float. A bundle should not be unreadable over missing quotes.+testReadBundleVersionUnquoted :: IO (Either Text ())+testReadBundleVersionUnquoted = do+  unquoted <- versionOf [("index.md", "---\nokf_version: 0.2\n---\n\n# Root\n")]+  pure (assertEqual (Right (VersionDeclared (OkfVersion 0 2))) unquoted)++versionOf :: [(FilePath, Text)] -> IO (Either BundleError VersionDeclaration)+versionOf files =+  withDiscoveryTree "okf-version" files readBundleVersion++-- | Index generation rewrites the bundle root's @index.md@, so without reading+-- the existing declaration first a single write destroys it. Fails on the code+-- that preceded this test.+testWriteBundleIndexesPreservesVersion :: IO (Either Text ())+testWriteBundleIndexesPreservesVersion =+  withDiscoveryTree+    "okf-version-preserve"+    [ ("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Root\n"),+      ("tables/orders.md", typedConcept "Orders")+    ]+    ( \root -> do+        written <- writeBundleIndexes root+        rootIndex <- Text.IO.readFile (root </> "index.md")+        tablesIndex <- Text.IO.readFile (root </> "tables" </> "index.md")+        declaration <- readBundleVersion root+        pure+          ( do+              firstShow written+              assertEqual (Right (VersionDeclared (OkfVersion 0 2))) declaration+              assertBool "root index keeps the declaration" ("okf_version: \"0.2\"" `Text.isInfixOf` rootIndex)+              assertBool "root index still lists subdirectories" ("[tables/](tables/index.md)" `Text.isInfixOf` rootIndex)+              assertBool "only the root index carries frontmatter" (not ("---" `Text.isInfixOf` tablesIndex))+          )+    )++-- | An explicit declaration is written where there was none; a bundle that+-- declares nothing keeps a frontmatter-free root index.+testWriteBundleIndexesDeclaresVersion :: IO (Either Text ())+testWriteBundleIndexesDeclaresVersion =+  withDiscoveryTree+    "okf-version-declare"+    [("tables/orders.md", typedConcept "Orders")]+    ( \root -> do+        untouched <- writeBundleIndexes root+        withoutDeclaration <- Text.IO.readFile (root </> "index.md")+        declared <- writeBundleIndexesWith (Just (OkfVersion 0 2)) root+        withDeclaration <- Text.IO.readFile (root </> "index.md")+        pure+          ( do+              firstShow untouched+              firstShow declared+              assertBool "undeclared bundle gets no frontmatter" (not ("---" `Text.isInfixOf` withoutDeclaration))+              assertEqual+                ("---\nokf_version: \"0.2\"\n---\n\n" <> withoutDeclaration)+                withDeclaration+          )+    )++testFixtureValidBundle :: IO (Either Text ())+testFixtureValidBundle = do+  root <- fixturePath "valid-bundle"+  concepts <- readBundle root+  inventory <- readBundleInventory root+  declaration <- readBundleVersion root+  pure+    ( do+        orders <- firstShow (parseConceptId "tables/orders")+        customers <- firstShow (parseConceptId "tables/customers")+        sales <- firstShow (parseConceptId "datasets/sales")+        assertEqual 4 (length concepts)+        assertEqual [] (foldMap (validateDocument PermissiveConformance . conceptDocument) concepts)+        -- The primary fixture is a v0.2 bundle: it declares the version and+        -- every concept dates itself with `generated` rather than the+        -- superseded `timestamp`.+        assertEqual (Right (VersionDeclared (OkfVersion 0 2))) declaration+        assertEqual [] (validateBundle StrictAuthoring (VersionDeclared (OkfVersion 0 2)) inventory concepts)+        assertBool+          "every concept carries generated"+          (all (isJust . conceptGenerated) concepts)+        let graph = buildGraph concepts+        assertBool "orders to customers" (Edge {source = orders, target = customers} `List.elem` edges graph)+        assertBool "orders to sales" (Edge {source = orders, target = sales} `List.elem` edges graph)+    )++-- | The v0.1 fallback of @docs\/adr\/7-okf-v0-1-legacy-fallback-policy.md@ needs+-- a bundle in the old shape or it will rot. This fixture is that bundle, and is+-- deliberately never migrated: it dates its concept with the superseded+-- @timestamp@ and declares no @okf_version@, so strict validation must report+-- nothing at all.+testFixtureV01LegacyBundle :: IO (Either Text ())+testFixtureV01LegacyBundle = do+  root <- fixturePath "v01-legacy-bundle"+  concepts <- readBundle root+  inventory <- readBundleInventory root+  declaration <- readBundleVersion root+  pure+    ( do+        assertEqual 1 (length concepts)+        assertEqual (Right VersionUndeclared) declaration+        assertEqual [] (validateBundle StrictAuthoring VersionUndeclared inventory concepts)+        assertBool+          "the concept carries no generated family"+          (all (isNothing . conceptGenerated) concepts)+        -- The date is still read, which is the whole point of the fallback.+        assertEqual ["2026-06-16"] (staleConceptDate <$> logStaleness concepts [])+    )++testFixtureGraphJsonShape :: IO (Either Text ())+testFixtureGraphJsonShape = do+  root <- fixturePath "valid-bundle"+  concepts <- readBundle root+  orders <- requireConceptIO "tables/orders" concepts+  pure+    ( case filter (\Node {id = nodeId} -> nodeId == conceptIdOf orders) (nodes (buildGraph concepts)) of+        [ordersNode] ->+          assertEqual+            ( object+                [ "id" .= ("tables/orders" :: Text),+                  "label" .= ("Orders" :: Text),+                  "type" .= ("BigQuery Table" :: Text),+                  "description" .= Just ("Order fact table." :: Text),+                  "resource" .= Just ("bigquery://analytics.tables.orders" :: Text),+                  "tags" .= ["orders" :: Text, "sales"]+                ]+            )+            (toJSON ordersNode)+        other -> Left ("expected one orders node, got " <> Text.pack (show (length other)))+    )++testFixtureUnterminatedFrontmatter :: IO (Either Text ())+testFixtureUnterminatedFrontmatter = do+  root <- fixturePath "invalid-unterminated-frontmatter"+  result <- walkBundle root+  pure+    ( case result of+        Left (InvalidConceptDocument "broken.md" UnterminatedFrontmatter) -> Right ()+        other -> Left ("expected unterminated frontmatter error, got " <> Text.pack (show other))+    )++testFixtureMissingType :: IO (Either Text ())+testFixtureMissingType = do+  root <- fixturePath "invalid-missing-type"+  concepts <- readBundle root+  pure+    ( do+        assertEqual 1 (length concepts)+        case foldMap (validateDocument PermissiveConformance . conceptDocument) concepts of+          [MissingRequiredField "type"] -> Right ()+          other -> Left ("expected missing type error, got " <> Text.pack (show other))+    )++testFrontmatterBuilderRoundTrip :: Either Text ()+testFrontmatterBuilderRoundTrip = do+  let generatedValue = Generated (parseActor "reference_agent/gemini-2.5-pro") (Just "2026-06-20T22:53:05Z")+      frontmatterValue =+        setField "version" (String "0.2.0")+          . setTags ["orders", "sales"]+          . setResource "bigquery://analytics.tables.orders"+          . setGenerated generatedValue+          $ okfCommon+            OkfCommon+              { commonType = "BigQuery Table",+                commonTitle = Just "Orders",+                commonDescription = Just "Order fact table.",+                commonTimestamp = Just "2026-06-16T00:00:00Z"+              }+      original = OKFDocument frontmatterValue "# Orders\n\nBody text.\n"+  reparsed <- firstShow (parseDocument (serializeDocument original))+  assertEqual (original ^. #frontmatter) (reparsed ^. #frontmatter)+  assertEqual (body original) (body reparsed)+  -- The v0.2 family survives serialize-then-parse as a typed value, not merely+  -- as equal frontmatter, and a `generated` without `at` round-trips too.+  assertEqual (Just generatedValue) (readGenerated (reparsed ^. #frontmatter))+  let withoutAt = setGenerated (Generated (HumanActor "ahormati") Nothing) emptyFrontmatter+  reparsedWithoutAt <- firstShow (parseDocument (serializeDocument (OKFDocument withoutAt "# Orders\n")))+  assertEqual+    (Just (Generated (HumanActor "ahormati") Nothing))+    (readGenerated (reparsedWithoutAt ^. #frontmatter))++testSerializeDeterministicKeyOrder :: Either Text ()+testSerializeDeterministicKeyOrder = do+  let frontmatterValue =+        setField "zeta" (String "z")+          . setField "alpha" (String "a")+          . setTags ["t"]+          . setResource "res://x"+          . setType "Recipe"+          . setTimestamp "2026-06-16T00:00:00Z"+          . setDescription "Desc"+          . setTitle "Demo"+          $ emptyFrontmatter+      rendered = serializeDocument (OKFDocument frontmatterValue "# Demo\n")+      expectedOrder =+        ["type:", "title:", "description:", "resource:", "tags:", "timestamp:", "alpha:", "zeta:"]+  keyIndices <- traverse (\key -> maybe (Left ("missing key " <> key)) Right (substringIndex key rendered)) expectedOrder+  assertBool ("keys not in deterministic order: " <> Text.pack (show keyIndices)) (strictlyIncreasing keyIndices)++-- | The v0.2 @generated@ family sorts before the v0.1 @timestamp@ it supersedes+-- (specification section 13.1), so a document carrying both reads with the+-- current field first.+testSerializeGeneratedBeforeTimestamp :: Either Text ()+testSerializeGeneratedBeforeTimestamp = do+  let frontmatterValue =+        setTimestamp "2026-06-16T00:00:00Z"+          . setField "generated" (object ["by" .= ("human:ahormati" :: Text), "at" .= ("2026-06-20T22:53:05Z" :: Text)])+          . setType "Recipe"+          $ emptyFrontmatter+      rendered = serializeDocument (OKFDocument frontmatterValue "# Demo\n")+      expectedOrder = ["type:", "generated:", "timestamp:"]+  keyIndices <- traverse (\key -> maybe (Left ("missing key " <> key)) Right (substringIndex key rendered)) expectedOrder+  assertBool ("keys not in deterministic order: " <> Text.pack (show keyIndices)) (strictlyIncreasing keyIndices)++-- | Footnotes are enabled at every parse site, and the observable proof is a+-- link that no longer appears.+--+-- With footnotes disabled a single-token footnote definition such as+-- @[^src]: tables\/orders.md@ is read as a CommonMark /link reference+-- definition/, which turns its citation @[^src]@ into a link whose destination+-- is that token. That phantom link reached 'extractConceptLinks' and was then+-- reported as a dangling reference. Enabling footnotes removes it while leaving+-- an ordinary link in the same body alone.+testFootnotesEnabled :: Either Text ()+testFootnotesEnabled = do+  ordersId <- parseTestConceptId "tables/orders"+  usersId <- parseTestConceptId "tables/users"+  concept <-+    testConcept+      "source"+      ( "See the note.[^src] Also see "+          <> renderConceptLink usersId "users"+          <> ".\n\n[^src]: tables/orders.md\n"+      )+  assertEqual [usersId] (extractConceptLinks concept)+  assertBool+    "footnote definition must not become a link reference definition"+    (ordersId `notElem` extractConceptLinks concept)++-- | Enabling footnotes changes the parse tree every body walker sees, so pin+-- the two walkers that do not care about footnotes at all: log parsing and link+-- extraction. Bracket-heavy prose in a log bullet must still yield one entry+-- with its text intact, and a body whose links sit inside a /cited/ footnote+-- definition must still contribute those links to the graph.+testFootnotesDoNotRegressLogsOrLinks :: Either Text ()+testFootnotesDoNotRegressLogsOrLinks = do+  let parsed = parseLog "# Log\n\n## 2026-06-23\n* **Update**: renamed [orders] to [^orders].\n"+  -- The backslashes are 'Okf.Log.renderInlineNodes' round-tripping inline nodes+  -- through @nodeToCommonmark@, which escapes brackets so the text re-parses to+  -- itself. That predates footnotes and is unchanged by them: an uncited+  -- @[^orders]@ is plain text under either parse configuration.+  assertEqual+    [LogDay "2026-06-23" [LogEntry (Just "Update") "renamed \\[orders\\] to \\[^orders\\]."]]+    (logDays parsed)+  usersId <- parseTestConceptId "tables/users"+  concept <-+    testConcept+      "source"+      ( "Attributed claim.[^cited]\n\n[^cited]: See "+          <> renderConceptLink usersId "users"+          <> " for detail.\n"+      )+  assertEqual [usersId] (extractConceptLinks concept)++-- | Labels come from a real parse, not a naive text scan: footnote syntax+-- inside an inline code span, an indented code block, or a fenced code block+-- yields nothing.+testExtractFootnoteLabelsIgnoresCode :: Either Text ()+testExtractFootnoteLabelsIgnoresCode = do+  let body =+        Text.unlines+          [ "Sharded daily.[^ga4-schema] Not a footnote: `[^inline-code]`.",+            "",+            "    [^indented-block]: not a footnote either",+            "",+            "```sql",+            "SELECT 1 -- [^fenced-block]: not a footnote",+            "```",+            "",+            "Undefined citation.[^never-defined]",+            "",+            "[^ga4-schema]: GA4 BigQuery Export schema"+          ]+      labels = extractFootnoteLabels body+  assertEqual ["ga4-schema", "never-defined"] (footnoteReferences labels)+  assertEqual ["ga4-schema"] (footnoteDefinitions labels)+  assertEqual ["ga4-schema", "never-defined"] (footnoteLabelsUsed labels)++-- | The two labels cmark-gfm erases are exactly the two an author most needs+-- reported, so extraction must keep both: a citation with no definition (which+-- the parser reverts to plain text) and a definition nothing cites (which the+-- parser deletes outright). The ordinal guard is the same test's second job —+-- cmark-gfm renumbers a matched reference to @"1"@, so a label that parses as a+-- bare integer would mean extraction had drifted back onto the parse tree.+testExtractFootnoteLabelsKeepsErasedLabels :: Either Text ()+testExtractFootnoteLabelsKeepsErasedLabels = do+  let body =+        Text.unlines+          [ "Matched.[^matched] Undefined.[^undefined]",+            "",+            "[^matched]: a definition that is cited",+            "",+            "[^uncited]: a definition that nothing cites"+          ]+      labels = extractFootnoteLabels body+  assertEqual ["matched", "undefined"] (footnoteReferences labels)+  assertEqual ["matched", "uncited"] (footnoteDefinitions labels)+  assertBool+    "no extracted label may be a bare ordinal"+    (not (any looksLikeInteger (footnoteLabelsUsed labels)))+  where+    looksLikeInteger label =+      not (Text.null label) && Text.all (`Text.elem` "0123456789") label++-- | Specification §10.3's prose says "fenced" and §10.2's own worked example+-- writes an indented block, so both count; and the section is bounded at the+-- next heading of the same or a shallower level, so a fenced block under a later+-- @# Notes@ heading is not a second computation while one under a nested+-- @## Subsection@ still belongs to the section.+testComputationBlocks :: Either Text ()+testComputationBlocks = do+  assertEqual+    ["SELECT 1\n"]+    (computationBlocks (Text.unlines ["# Computation", "", "    SELECT 1"]))+  assertEqual+    ["SELECT 1\n"]+    (computationBlocks (Text.unlines ["# Computation", "", "```sql", "SELECT 1", "```"]))+  assertEqual+    ["SELECT 1\n"]+    ( computationBlocks+        ( Text.unlines+            [ "# Computation",+              "",+              "    SELECT 1",+              "",+              "# Notes",+              "",+              "```sql",+              "SELECT 2",+              "```"+            ]+        )+    )+  assertEqual+    ["SELECT 1\n", "SELECT 2\n"]+    ( computationBlocks+        ( Text.unlines+            [ "# Computation",+              "",+              "    SELECT 1",+              "",+              "## Explanation",+              "",+              "```sql",+              "SELECT 2",+              "```"+            ]+        )+    )+  assertEqual+    ["SELECT 1\n", "SELECT 2\n"]+    ( computationBlocks+        ( Text.unlines+            ["# Computation", "", "```sql", "SELECT 1", "```", "", "```sql", "SELECT 2", "```"]+        )+    )+  assertEqual+    []+    (computationBlocks (Text.unlines ["# Notes", "", "```sql", "SELECT 1", "```"]))+  assertEqual+    ["SELECT 1\n"]+    (computationBlocks (Text.unlines ["##  computation ", "", "    SELECT 1"]))++-- | The one erasure that reaches 'computationBlocks', pinned so that meeting it+-- later is recognized rather than investigated. Per+-- @docs/adr/9-one-markdown-parse-configuration-and-source-scanned-authoring-checks.md@,+-- okf parses every body with footnotes enabled and cmark-gfm deletes a footnote+-- definition nothing cites, content and all — so a computation hidden inside one+-- is invisible here. The document is malformed in a second, unrelated way, so+-- this is an accepted cost rather than a bug to work around.+testComputationBlocksFootnoteHazard :: Either Text ()+testComputationBlocksFootnoteHazard =+  assertEqual+    []+    ( computationBlocks+        ( Text.unlines+            ["# Computation", "", "[^unused]: a definition nothing cites", "", "    SELECT 1"]+        )+    )++testConceptLinkRoundTrip :: Either Text ()+testConceptLinkRoundTrip = do+  sourceId <- parseTestConceptId "recipes/haskell-library-repo"+  let targetStrings = ["orders", "modules/nix-haskell-flake", "refs/source-system.v1"]+  mapM_+    ( \rawTarget -> do+        targetId <- parseTestConceptId rawTarget+        let extracted = extractFromBodyLinkingTo sourceId targetId+        assertEqual [targetId] extracted+    )+    targetStrings++parseTestConceptId :: Text -> Either Text ConceptId+parseTestConceptId rawId =+  first (\err -> "bad concept id " <> rawId <> ": " <> Text.pack (show err)) (parseConceptId rawId)++extractFromBodyLinkingTo :: ConceptId -> ConceptId -> [ConceptId]+extractFromBodyLinkingTo sourceId targetId =+  extractConceptLinks+    (conceptFromDocument sourceId (OKFDocument (setType "Test" emptyFrontmatter) ("See " <> renderConceptLink targetId "link" <> ".\n")))++testRejectOverEscapingRelativeLink :: Either Text ()+testRejectOverEscapingRelativeLink = do+  sourceId <- parseTestConceptId "a/b/source"+  targetId <- parseTestConceptId "tables/orders"+  let concept =+        conceptFromDocument+          sourceId+          (OKFDocument (setType "Test" emptyFrontmatter) "[Escapes](../../../tables/orders.md)\n")+  assertEqual [] (extractConceptLinks concept)+  assertEqual [] (validateInMemoryBundle PermissiveConformance VersionUndeclared [concept, targetConcept targetId])+  where+    targetConcept targetId =+      conceptFromDocument+        targetId+        (OKFDocument (setType "Test" emptyFrontmatter) "# Orders\n")++-- | Specification §6.2: each path-valued field accepts an absolute URL, a+-- bundle-relative path beginning with @/@, or an ordinary relative path.+-- Classification is total, so a value that is none of the three lands on a named+-- alternative rather than being dropped.+testClassifyPathReference :: Either Text ()+testClassifyPathReference = do+  deep <- parseTestConceptId "metrics/finance/revenue"+  shallow <- parseTestConceptId "revenue"+  -- An absolute URL yields its case-folded scheme, whatever the scheme is: §6.2+  -- names no allowed set, so deciding that is the profile's job.+  assertEqual (ExternalUrl "https") (classifyPathReference deep "https://wiki.acme/revenue")+  assertEqual (ExternalUrl "mori") (classifyPathReference deep "mori://shinzui/okf")+  assertEqual (ExternalUrl "https") (classifyPathReference deep "HTTPS://wiki.acme/revenue")+  -- A leading slash resolves from the bundle root regardless of where the+  -- concept carrying the value lives.+  assertEqual (BundlePath "references/policy.md") (classifyPathReference deep "/references/policy.md")+  assertEqual (BundlePath "references/policy.md") (classifyPathReference shallow "/references/policy.md")+  -- A relative path resolves against the source concept's own directory.+  assertEqual+    (BundlePath "metrics/finance/policy.md")+    (classifyPathReference deep "policy.md")+  assertEqual+    (BundlePath "metrics/computations/revenue.md")+    (classifyPathReference deep "../computations/revenue.md")+  assertEqual (BundlePath "policy.md") (classifyPathReference shallow "./policy.md")+  -- A fragment or query suffix names the same target as the bare path.+  assertEqual (BundlePath "references/policy.md") (classifyPathReference deep "/references/policy.md#recognition")+  assertEqual (BundlePath "references/policy.md") (classifyPathReference deep "/references/policy.md?v=2")+  -- Non-Markdown targets classify identically; only the caller cares about the+  -- extension.+  assertEqual+    (BundlePath "references/attesters/revenue.py")+    (classifyPathReference deep "/references/attesters/revenue.py")+  -- Climbing above the bundle root is its own outcome, distinct from malformed:+  -- the author wrote a well-formed relative path that points outside.+  assertEqual EscapesBundle (classifyPathReference shallow "../../etc/passwd")+  assertEqual EscapesBundle (classifyPathReference deep "../../../../elsewhere.md")+  -- Text that names nothing at all.+  assertEqual MalformedPath (classifyPathReference deep "")+  assertEqual MalformedPath (classifyPathReference deep "   ")+  assertEqual MalformedPath (classifyPathReference deep "#recognition")+  -- 'collapseBundlePath' is exported for the same reason it is shared: one+  -- spelling of "does this climb out of the bundle".+  assertEqual (Just "references/policy.md") (collapseBundlePath "references/./policy.md")+  assertEqual (Just "policy.md") (collapseBundlePath "references/../policy.md")+  assertEqual Nothing (collapseBundlePath "../policy.md")++-- | The seam 'Okf.Path' deliberately left open: classification says what shape a+-- value has, resolution says whether the thing it names is there. The predicate+-- stands in for a 'BundleInventory' so the two can be tested apart.+testResolvePathReference :: Either Text ()+testResolvePathReference = do+  deep <- parseTestConceptId "metrics/finance/revenue"+  shallow <- parseTestConceptId "revenue"+  let present =+        [ "references/policy.md",+          "references/attesters/revenue.py",+          "metrics/finance/policy.md",+          "sibling.md"+        ]+      exists = (`elem` present)+      resolve = resolvePathReference exists+  -- Every scheme counts, not only the three 'Okf.Graph.isExternalUrl' knows+  -- about, and okf never fetches any of them.+  assertEqual (ResolvedExternal "https") (resolve deep "https://wiki.acme/revenue")+  assertEqual (ResolvedExternal "bigquery") (resolve deep "bigquery://analytics.tables.orders")+  -- A leading slash resolves from the bundle root wherever the concept lives.+  assertEqual (ResolvedInBundle "references/policy.md") (resolve deep "/references/policy.md")+  assertEqual (ResolvedInBundle "references/policy.md") (resolve shallow "/references/policy.md")+  -- A relative path resolves against the carrying concept's own directory.+  assertEqual (ResolvedInBundle "metrics/finance/policy.md") (resolve deep "policy.md")+  assertEqual (ResolvedInBundle "sibling.md") (resolve shallow "./sibling.md")+  -- The case this whole plan exists for: a non-Markdown target resolves, which+  -- is only possible because the inventory sees more than concepts.+  assertEqual+    (ResolvedInBundle "references/attesters/revenue.py")+    (resolve deep "/references/attesters/revenue.py")+  -- Nothing there under that name.+  assertEqual (DanglingInBundle "references/deleted.md") (resolve deep "/references/deleted.md")+  assertEqual (DanglingInBundle "metrics/computations/revenue.md") (resolve deep "../computations/revenue.md")+  -- Distinct outcomes for a value that could never name anything in the bundle.+  assertEqual UnresolvableEscape (resolve shallow "../../etc/passwd")+  assertEqual UnresolvableMalformed (resolve deep "")+  assertEqual UnresolvableMalformed (resolve deep "   ")++-- | The version-metadata lists name keys okf actually owns. Nothing else would+-- catch a typo in one of those string literals: a misspelled entry simply never+-- matches a rule, so the check it drives goes quietly missing.+testVersionedFieldsAreCoreFields :: Either Text ()+testVersionedFieldsAreCoreFields = do+  assertEqual [] (filter (`Set.notMember` coreFrontmatterFields) fieldsIntroducedInV02)+  assertEqual [] (filter (`Set.notMember` coreFrontmatterFields) fieldsSupersededInV02)+  -- The two lists are about different versions of the same key set and must not+  -- overlap: a key cannot be both introduced and superseded by v0.2.+  assertEqual [] (filter (`elem` fieldsSupersededInV02) fieldsIntroducedInV02)++-- | Specification §12: a known major with a higher minor is read as the highest+-- version okf understands within that major, because a minor bump is defined as+-- backward-compatible additions. An unknown major is read with no+-- version-specific rules at all.+testVersionGate :: Either Text ()+testVersionGate = do+  assertEqual Nothing (gateEffective (versionGate VersionUndeclared))+  assertEqual Nothing (gateEffective (versionGate (VersionUnparseable "zero point two")))+  assertEqual (Just (OkfVersion 0 1)) (gateEffective (versionGate (VersionDeclared (OkfVersion 0 1))))+  assertEqual (Just (OkfVersion 0 2)) (gateEffective (versionGate (VersionDeclared (OkfVersion 0 2))))+  assertEqual (Just (OkfVersion 0 2)) (gateEffective (versionGate (VersionDeclared (OkfVersion 0 3))))+  assertEqual Nothing (gateEffective (versionGate (VersionDeclared (OkfVersion 1 0))))+  assertEqual (Just "1.0") (gateNotUnderstood (versionGate (VersionDeclared (OkfVersion 1 0))))+  assertEqual Nothing (gateNotUnderstood (versionGate (VersionDeclared (OkfVersion 0 3))))+  assertBool "0.2 satisfies at-least 0.2" (gateDeclaresAtLeast (OkfVersion 0 2) (versionGate (VersionDeclared (OkfVersion 0 2))))+  assertBool "0.1 does not satisfy at-least 0.2" (not (gateDeclaresAtLeast (OkfVersion 0 2) (versionGate (VersionDeclared (OkfVersion 0 1)))))+  assertBool "undeclared satisfies nothing" (not (gateDeclaresAtLeast (OkfVersion 0 2) (versionGate VersionUndeclared)))++-- | The asymmetry this plan exists for: the v0.1 fallback stays unconditional,+-- but a bundle that has declared v0.2 and still carries @timestamp@ is+-- reporting an authoring mistake.+testLegacyFieldInDeclaredV2 :: Either Text ()+testLegacyFieldInDeclaredV2 = do+  conceptId <- parseTestConceptId "tables/orders"+  legacyOnly <-+    testConceptWithFrontmatter+      "tables/orders"+      "type: Test\ntitle: Title\ndescription: Description\ntimestamp: \"2026-06-16T00:00:00Z\"\n"+  migrated <-+    testConceptWithFrontmatter+      "tables/orders"+      "type: Test\ntitle: Title\ndescription: Description\ngenerated:\n  by: okf/0.4\n  at: \"2026-06-16T00:00:00Z\"\n"+  let declaredV2 = VersionDeclared (OkfVersion 0 2)+  assertEqual [] (validateInMemoryBundle StrictAuthoring VersionUndeclared [legacyOnly])+  assertEqual [] (validateInMemoryBundle PermissiveConformance declaredV2 [legacyOnly])+  assertEqual+    [DocumentInvalid conceptId (LegacyFieldInDeclaredV2 "timestamp")]+    (validateInMemoryBundle StrictAuthoring declaredV2 [legacyOnly])+  assertEqual [] (validateInMemoryBundle StrictAuthoring declaredV2 [migrated])+  -- An unknown major applies no version-specific rule, so the same document is+  -- read the way an undeclared bundle's would be.+  assertEqual+    [BundleVersionNotUnderstood "1.0"]+    (validateInMemoryBundle StrictAuthoring (VersionDeclared (OkfVersion 1 0)) [legacyOnly])++-- | §12: "Consumers that do not understand the declared version SHOULD attempt+-- best-effort consumption rather than refusing the bundle." Neither an+-- unreadable value nor an unknown major stops the bundle being read, and+-- neither is reported outside strict authoring.+testVersionDeclarationLints :: Either Text ()+testVersionDeclarationLints = do+  -- A migrated concept, so the only diagnostics here are version ones.+  concept <-+    testConceptWithFrontmatter+      "a"+      "type: Test\ntitle: Title\ndescription: Description\ngenerated:\n  by: okf/0.4\n  at: \"2026-06-16T00:00:00Z\"\n"+  assertEqual [] (validateInMemoryBundle PermissiveConformance (VersionUnparseable "0.x") [concept])+  assertEqual [] (validateInMemoryBundle PermissiveConformance (VersionDeclared (OkfVersion 1 0)) [concept])+  assertEqual+    [BundleVersionUnparseable "0.x"]+    (validateInMemoryBundle StrictAuthoring (VersionUnparseable "0.x") [concept])+  assertEqual+    [BundleVersionNotUnderstood "1.0"]+    (validateInMemoryBundle StrictAuthoring (VersionDeclared (OkfVersion 1 0)) [concept])+  -- A higher minor within a known major is a supported case, not a problem.+  assertEqual [] (validateInMemoryBundle StrictAuthoring (VersionDeclared (OkfVersion 0 3)) [concept])++testValidateBundleDanglingReference :: Either Text ()+testValidateBundleDanglingReference = do+  aId <- parseTestConceptId "a"+  bId <- parseTestConceptId "b"+  conceptA <- testConcept "a" ("See " <> renderConceptLink bId "b" <> ".\n")+  assertEqual [DanglingReference aId bId] (validateInMemoryBundle StrictAuthoring VersionUndeclared [conceptA])++testValidateBundleAcceptsResolved :: Either Text ()+testValidateBundleAcceptsResolved = do+  bId <- parseTestConceptId "b"+  conceptA <- testConcept "a" ("See " <> renderConceptLink bId "b" <> ".\n")+  conceptB <- testConcept "b" "Standalone.\n"+  assertEqual [] (validateInMemoryBundle StrictAuthoring VersionUndeclared [conceptA, conceptB])++-- | The §6.2 path check, at the level where its placement decisions live: strict+-- only, dangling only, and never over @sources[].resource@.+testValidateBundleDanglingFrontmatterPath :: Either Text ()+testValidateBundleDanglingFrontmatterPath = do+  aId <- parseTestConceptId "a"+  conceptB <- testConcept "b" "Standalone.\n"+  let withResource value =+        testConceptWithFrontmatter+          "a"+          ( "type: Test\ntitle: Title\ndescription: Description\n"+              <> "generated:\n  by: okf/0.4\n  at: \"2026-06-16T00:00:00Z\"\n"+              <> "resource: "+              <> value+              <> "\n"+          )+      strict concepts = validateInMemoryBundle StrictAuthoring VersionUndeclared concepts+      permissive concepts = validateInMemoryBundle PermissiveConformance VersionUndeclared concepts+  danglingResource <- withResource "/references/deleted.md"+  resolvedResource <- withResource "/b.md"+  externalResource <- withResource "bigquery://analytics.tables.orders"+  escapingResource <- withResource "../../elsewhere.md"+  assertEqual+    [DanglingFrontmatterPath aId "resource" "references/deleted.md" Nothing]+    (strict [danglingResource, conceptB])+  -- §11 forbids rejecting a bundle over a broken cross-link, so nothing is+  -- reported outside strict authoring.+  assertEqual [] (permissive [danglingResource, conceptB])+  assertEqual [] (strict [resolvedResource, conceptB])+  -- okf has no network access and never fetches, so an absolute URL is as+  -- resolved as it gets — whatever its scheme.+  assertEqual [] (strict [externalResource, conceptB])+  -- Escaping is deliberately unreported: a bare §4.1 URI such as+  -- @analytics.tables.orders@ classifies as a bundle path, so reporting any+  -- outcome other than dangling would fire on correct documents.+  assertEqual [] (strict [escapingResource, conceptB])+  -- The finding that scoped this check: §5.1 sanctions a scope descriptor as a+  -- @sources[].resource@, and @examples\/ddd-ordering@ carries one. Treating it+  -- as a path would report a correct bundle as broken.+  scopeDescriptor <-+    testConceptWithFrontmatter+      "a"+      ( "type: Test\ntitle: Title\ndescription: Description\n"+          <> "generated:\n  by: okf/0.4\n  at: \"2026-06-16T00:00:00Z\"\n"+          <> "sources:\n"+          <> "  - resource: all order-domain terms agreed in the ordering team's glossary reviews\n"+      )+  assertEqual [] (strict [scopeDescriptor, conceptB])++-- | The bundle-relative hint of specification §10.2's own worked example: a+-- relative path that resolves to nothing, where the same text read from the+-- bundle root names a file that is there.+--+-- §6.2 resolution is unchanged — the diagnostic still names what the value+-- actually resolved to. The fourth field only says what the author probably+-- meant.+testDanglingFrontmatterPathAlternative :: Either Text ()+testDanglingFrontmatterPathAlternative = do+  computationId <- parseTestConceptId "computations/revenue"+  rootId <- parseTestConceptId "revenue"+  skill <- testConcept "references/skills/run-on-bq" "Run instructions.\n"+  let withResource rawId value =+        testConceptWithFrontmatter+          rawId+          ( "type: Test\ntitle: Title\ndescription: Description\n"+              <> "generated:\n  by: okf/0.4\n  at: \"2026-06-16T00:00:00Z\"\n"+              <> "resource: "+              <> value+              <> "\n"+          )+      strict concepts = validateInMemoryBundle StrictAuthoring VersionUndeclared concepts+  -- The specification's own spelling, from a concept in a subdirectory.+  bareReference <- withResource "computations/revenue" "references/skills/run-on-bq.md"+  assertEqual+    [ DanglingFrontmatterPath+        computationId+        "resource"+        "computations/references/skills/run-on-bq.md"+        (Just "references/skills/run-on-bq.md")+    ]+    (strict [bareReference, skill])+  -- No root-anchored reading resolves either, so there is nothing to suggest.+  noTwin <- withResource "computations/revenue" "references/skills/nonexistent.md"+  assertEqual+    [ DanglingFrontmatterPath+        computationId+        "resource"+        "computations/references/skills/nonexistent.md"+        Nothing+    ]+    (strict [noTwin, skill])+  -- A value already written from the bundle root has no alternative reading.+  alreadyAnchored <- withResource "computations/revenue" "/references/skills/deleted.md"+  assertEqual+    [DanglingFrontmatterPath computationId "resource" "references/skills/deleted.md" Nothing]+    (strict [alreadyAnchored, skill])+  -- A concept at the bundle root resolves both readings to the same path, so+  -- there is never a hint: either the file is there and nothing is reported, or+  -- it is not and the alternative names the same missing path. The guard in+  -- 'bundleRelativeAlternative' is what keeps the second case from suggesting+  -- exactly what it just rejected.+  atRoot <- withResource "revenue" "references/skills/run-on-bq.md"+  assertEqual+    [DanglingFrontmatterPath rootId "resource" "references/skills/run-on-bq.md" Nothing]+    (strict [atRoot])+  assertEqual [] (strict [atRoot, skill])++testDuplicateConceptIds :: Either Text ()+testDuplicateConceptIds = do+  aId <- parseTestConceptId "a"+  conceptA <- testConcept "a" "First.\n"+  conceptAAgain <- testConcept "a" "Second.\n"+  assertEqual [aId] (duplicateConceptIds [conceptA, conceptAAgain])++-- | Build an in-memory concept via the public 'conceptFromDocument' constructor,+-- so its typed fields are derived from the frontmatter and cannot diverge.+-- Includes all StrictAuthoring fields so per-document validation passes and+-- bundle-level checks can be isolated.+testConcept :: Text -> Text -> Either Text Concept+testConcept rawId bodyText = do+  conceptId <- parseTestConceptId rawId+  let frontmatterValue =+        okfCommon+          OkfCommon+            { commonType = "Test",+              commonTitle = Just "Title",+              commonDescription = Just "Description",+              commonTimestamp = Just "2026-06-16T00:00:00Z"+            }+  pure (conceptFromDocument conceptId (OKFDocument frontmatterValue bodyText))++-- | Build a concept from raw frontmatter text, for cases where the frontmatter+-- carries families the 'OkfCommon' builder does not cover.+testConceptWithFrontmatter :: Text -> Text -> Either Text Concept+testConceptWithFrontmatter rawId frontmatterText = do+  conceptId <- parseTestConceptId rawId+  document <- firstShow (parseDocument ("---\n" <> frontmatterText <> "---\n\n# Test\n"))+  pure (conceptFromDocument conceptId document)++testConceptWithTimestamp :: Text -> Text -> Either Text Concept+testConceptWithTimestamp rawId timestamp = do+  conceptId <- parseTestConceptId rawId+  let frontmatterValue =+        okfCommon+          OkfCommon+            { commonType = "Test",+              commonTitle = Just "Title",+              commonDescription = Just "Description",+              commonTimestamp = Just timestamp+            }+  pure (conceptFromDocument conceptId (OKFDocument frontmatterValue "# Test\n"))++testConceptGeneratedProjection :: Either Text ()+testConceptGeneratedProjection = do+  conceptId <- parseTestConceptId "tables/orders"+  document <-+    firstShow+      ( parseDocument+          "---\ntype: BigQuery Table\ngenerated: { by: human:ahormati, at: 2026-06-20T22:53:05Z }\n---\n\n# Orders\n"+      )+  let concept = conceptFromDocument conceptId document+  assertEqual+    (Just (Generated (HumanActor "ahormati") (Just "2026-06-20T22:53:05Z")))+    (conceptGenerated concept)++testReadGeneratedWithoutActor :: Either Text ()+testReadGeneratedWithoutActor = do+  -- Section 5.2 makes `by` REQUIRED within `generated`, so a mapping without+  -- one is not a Generated. Reading is silent; reporting is validation's job.+  withoutBy <- firstShow (parseDocument "---\ntype: Recipe\ngenerated: { at: 2026-06-20T22:53:05Z }\n---\nBody\n")+  assertEqual Nothing (readGenerated (withoutBy ^. #frontmatter))+  notAMapping <- firstShow (parseDocument "---\ntype: Recipe\ngenerated: human:ahormati\n---\nBody\n")+  assertEqual Nothing (readGenerated (notAMapping ^. #frontmatter))+  -- `at` is not required within the mapping.+  withoutAt <- firstShow (parseDocument "---\ntype: Recipe\ngenerated: { by: reference_agent/gemini-2.5-pro }\n---\nBody\n")+  assertEqual+    (Just (Generated (ProducerActor "reference_agent" "gemini-2.5-pro") Nothing))+    (readGenerated (withoutAt ^. #frontmatter))++-- | Specification section 5.2 permits `verified` as a list or as a single bare+-- `{ by, at }` mapping, and section 11 makes normalising the bare form to a+-- one-element list a consumer MUST.+testReadVerifiedShapes :: Either Text ()+testReadVerifiedShapes = do+  let verifiedIn source = readVerified . (^. #frontmatter) <$> firstShow (parseDocument source)+  asList <-+    verifiedIn+      "---\ntype: Recipe\nverified:\n  - { by: human:ahormati, at: 2026-06-25T09:00:00Z }\n  - { by: process:finance-nightly, at: 2026-06-26T02:00:00Z }\n---\nBody\n"+  assertEqual+    [ Verification (HumanActor "ahormati") (Just "2026-06-25T09:00:00Z"),+      Verification (ProcessActor "finance-nightly") (Just "2026-06-26T02:00:00Z")+    ]+    asList+  bareMapping <- verifiedIn "---\ntype: Recipe\nverified: { by: human:ahormati, at: 2026-06-25T09:00:00Z }\n---\nBody\n"+  assertEqual [Verification (HumanActor "ahormati") (Just "2026-06-25T09:00:00Z")] bareMapping+  absent <- verifiedIn "---\ntype: Recipe\n---\nBody\n"+  assertEqual [] absent+  -- An entry without the `by` actor is skipped rather than yielding a partial+  -- Verification, mirroring readGenerated.+  partial <- verifiedIn "---\ntype: Recipe\nverified:\n  - { at: 2026-06-25T09:00:00Z }\n  - { by: human:ahormati }\n---\nBody\n"+  assertEqual [Verification (HumanActor "ahormati") Nothing] partial+  notAMapping <- verifiedIn "---\ntype: Recipe\nverified: human:ahormati\n---\nBody\n"+  assertEqual [] notAMapping++testVerifiedRoundTrip :: Either Text ()+testVerifiedRoundTrip = do+  let verifications =+        [ Verification (HumanActor "ahormati") (Just "2026-06-25T09:00:00Z"),+          Verification (ProcessActor "finance-nightly") Nothing+        ]+      original = OKFDocument (setVerified verifications (setType "Recipe" emptyFrontmatter)) "# Demo\n"+      rendered = serializeDocument original+  reparsed <- firstShow (parseDocument rendered)+  assertEqual verifications (readVerified (reparsed ^. #frontmatter))+  -- A single entry is still written as a list, not as the bare-mapping form.+  let single = OKFDocument (setVerified [Verification (HumanActor "ahormati") Nothing] emptyFrontmatter) "# Demo\n"+  assertBool+    ("single entry not written as a list: " <> serializeDocument single)+    (isJust (substringIndex "- by:" (serializeDocument single)))++testReadStatus :: Either Text ()+testReadStatus = do+  let statusIn source = readStatus . (^. #frontmatter) <$> firstShow (parseDocument source)+      withStatus value = statusIn ("---\ntype: Recipe\nstatus: " <> value <> "\n---\nBody\n")+  for_+    [("draft", Draft), ("stable", Stable), ("deprecated", Deprecated)]+    (\(text, expected) -> withStatus text >>= assertEqual expected)+  -- Section 5.4: "Absent `status` => `stable`."+  absent <- statusIn "---\ntype: Recipe\n---\nBody\n"+  assertEqual Stable absent+  -- Section 11 forbids rejecting for an unexpected optional value, and the+  -- original text must survive so renderStatus reproduces it.+  unknown <- withStatus "archived"+  assertEqual (UnknownStatus "archived") unknown+  assertEqual "archived" (renderStatus unknown)+  -- Case-sensitive, consistent with the section 7 actor convention.+  wrongCase <- withStatus "Stable"+  assertEqual (UnknownStatus "Stable") wrongCase+  -- renderStatus inverts readStatus on every value it can read back.+  for_+    [Draft, Stable, Deprecated, UnknownStatus "archived"]+    (\value -> withStatus (renderStatus value) >>= assertEqual value)++testReadStaleAfter :: Either Text ()+testReadStaleAfter = do+  let staleAfterIn source = readStaleAfter . (^. #frontmatter) <$> firstShow (parseDocument source)+  present <- staleAfterIn "---\ntype: Recipe\nstale_after: 2026-09-23\n---\nBody\n"+  assertEqual (Just "2026-09-23") present+  absent <- staleAfterIn "---\ntype: Recipe\n---\nBody\n"+  assertEqual Nothing absent+  -- Read verbatim and not parsed here: a malformed date must survive to be+  -- reported by Okf.Trust.staleness rather than vanish on serialization.+  malformed <- staleAfterIn "---\ntype: Recipe\nstale_after: not-a-date\n---\nBody\n"+  assertEqual (Just "not-a-date") malformed+  let built = setStaleAfter "2026-09-23" (setStatus Deprecated emptyFrontmatter)+  reparsed <- firstShow (parseDocument (serializeDocument (OKFDocument built "# Demo\n")))+  assertEqual (Just "2026-09-23") (readStaleAfter (reparsed ^. #frontmatter))+  assertEqual Deprecated (readStatus (reparsed ^. #frontmatter))++testTrustTier :: Either Text ()+testTrustTier = do+  let verifiedBy actor = Verification (parseActor actor) (Just "2026-06-25T09:00:00Z")+  -- Section 5.3: "No `verified` key => unverified."+  assertEqual Unverified (trustTier [])+  -- "`verified` by non-`human:` actors only => machine-confirmed."+  assertEqual MachineConfirmed (trustTier [verifiedBy "process:finance-nightly"])+  assertEqual MachineConfirmed (trustTier [verifiedBy "reference_agent/gemini-2.5-pro"])+  -- An actor matching none of the three section 7 shapes is still not a human.+  assertEqual MachineConfirmed (trustTier [verifiedBy "something"])+  -- "`verified` by a `human:<id>` actor => human-reviewed", including mixed.+  assertEqual HumanReviewed (trustTier [verifiedBy "human:ahormati"])+  assertEqual+    HumanReviewed+    (trustTier [verifiedBy "process:finance-nightly", verifiedBy "human:ahormati"])+  -- The Ord instance runs lowest to highest, as section 5.3 presents them.+  assertBool "tiers ordered lowest to highest" (Unverified < MachineConfirmed && MachineConfirmed < HumanReviewed)++testLatestVerification :: Either Text ()+testLatestVerification = do+  -- Section 5.2: "'How recently' is the latest `at`."+  assertEqual+    (Just "2026-06-26T02:00:00Z")+    ( latestVerification+        [ Verification (HumanActor "ahormati") (Just "2026-06-25T09:00:00Z"),+          Verification (ProcessActor "finance-nightly") (Just "2026-06-26T02:00:00Z")+        ]+    )+  -- Entries without an `at` are skipped rather than losing the whole result.+  assertEqual+    (Just "2026-06-25T09:00:00Z")+    ( latestVerification+        [ Verification (ProcessActor "nightly") Nothing,+          Verification (HumanActor "ahormati") (Just "2026-06-25T09:00:00Z")+        ]+    )+  assertEqual Nothing (latestVerification [])+  assertEqual Nothing (latestVerification [Verification (HumanActor "ahormati") Nothing])++testStaleness :: Either Text ()+testStaleness = do+  let today = fromGregorian 2026 6 15+  assertEqual NoStaleAfter (staleness today Nothing)+  -- Section 5.5: "A concept is stale when `today >= stale_after`."+  assertEqual (Stale (fromGregorian 2026 6 1)) (staleness today (Just "2026-06-01"))+  -- The boundary: equal to today is stale, not fresh. An off-by-one here is a+  -- real bug, so it is asserted explicitly.+  assertEqual (Stale (fromGregorian 2026 6 15)) (staleness today (Just "2026-06-15"))+  assertEqual Fresh (staleness today (Just "2026-06-16"))+  assertEqual Fresh (staleness today (Just "2026-09-23"))+  -- A malformed deadline is surfaced, never silently treated as fresh.+  assertEqual (StaleAfterUnparseable "not-a-date") (staleness today (Just "not-a-date"))+  assertEqual (StaleAfterUnparseable "2026-13-01") (staleness today (Just "2026-13-01"))+  assertEqual "stale since 2026-06-01" (renderStaleness (staleness today (Just "2026-06-01")))+  assertEqual "ok" (renderStaleness (staleness today (Just "2026-09-23")))++-- | A document exercising both usage-window scopes, both credibility-signal+-- shapes, a scope-descriptor resource, and an entry missing the one key+-- section 5.1 requires within an entry.+sourcesFixtureDocument :: Text+sourcesFixtureDocument =+  Text.unlines+    [ "---",+      "type: BigQuery Table",+      "sources:",+      "  - id: ga4-schema",+      "    resource: https://developers.google.com/analytics/bigquery/export-schema",+      "    title: GA4 BigQuery Export schema",+      "    author: team:ga4-docs",+      "    usage_count: 5000",+      "    last_modified: 2026-05-30",+      "  - id: exec-dash",+      "    resource: dashboards/exec-revenue",+      "    usage_count: 12",+      "    usage_window: { from: 2026-01-01, to: 2026-01-31 }",+      "  - id: broad-scope",+      "    resource: all queries in BigQuery project X",+      "    usage_count: \"5000\"",+      "  - id: no-resource",+      "    title: Missing the required key",+      "usage_window: { from: 2026-06-01, to: 2026-06-30 }",+      "---",+      "",+      "# Orders"+    ]++-- | Specification §5.1 makes the footnote label the join key into @sources@, so+-- strict validation checks it in both directions: a label naming no entry is a+-- defect, and an entry whose id nothing cites is a lint. Neither fires in+-- permissive mode, because §11 forbids rejecting a bundle over optional+-- frontmatter.+testFootnoteAttributionJoin :: Either Text ()+testFootnoteAttributionJoin = do+  let document mistyped =+        Text.unlines+          [ "---",+            "type: BigQuery Table",+            "title: Orders",+            "description: Order fact table.",+            "generated: { by: okf-agent/1.0, at: 2026-07-31T00:00:00Z }",+            "sources:",+            "  - id: ga4-schema",+            "    resource: https://developers.google.com/analytics/bigquery/export-schema",+            "  - id: uncited-policy",+            "    resource: https://wiki.acme/finance/revenue-recognition",+            "---",+            "",+            "Sharded daily.[^" <> mistyped <> "]",+            "",+            "[^" <> mistyped <> "]: GA4 BigQuery Export schema"+          ]+  mistypedDocument <- firstShow (parseDocument (document "ga4-schmea"))+  assertEqual+    [ FootnoteLabelNotInSources "ga4-schmea",+      SourceIdNotCited "ga4-schema",+      SourceIdNotCited "uncited-policy"+    ]+    (validateDocument StrictAuthoring mistypedDocument)+  assertEqual [] (validateDocument PermissiveConformance mistypedDocument)+  -- Correcting the citation clears the defect and one of the two lints.+  correctedDocument <- firstShow (parseDocument (document "ga4-schema"))+  assertEqual+    [SourceIdNotCited "uncited-policy"]+    (validateDocument StrictAuthoring correctedDocument)++-- | Markdown footnotes are ordinary prose used for ordinary purposes. A document+-- that has not opted into structured provenance is making no attribution claim,+-- so a body full of footnotes must report nothing in either mode.+testFootnoteAttributionSkippedWithoutSources :: Either Text ()+testFootnoteAttributionSkippedWithoutSources = do+  document <-+    firstShow+      ( parseDocument+          ( Text.unlines+              [ "---",+                "type: BigQuery Table",+                "title: Orders",+                "description: Order fact table.",+                "generated: { by: okf-agent/1.0, at: 2026-07-31T00:00:00Z }",+                "---",+                "",+                "An aside.[^aside] Another.[^undefined]",+                "",+                "[^aside]: just a footnote, not an attribution"+              ]+          )+      )+  assertEqual [] (validateDocument StrictAuthoring document)+  assertEqual [] (validateDocument PermissiveConformance document)++testReadSources :: Either Text ()+testReadSources = do+  document <- firstShow (parseDocument sourcesFixtureDocument)+  let sources = readSources (document ^. #frontmatter)+  -- The entry with no `resource` is skipped: section 5.1 makes it REQUIRED+  -- within an entry, and reporting it is validation's job, not the reader's.+  assertEqual [Just "ga4-schema", Just "exec-dash", Just "broad-scope"] (map sourceId sources)+  case sources of+    (first_ : _) -> do+      assertEqual "https://developers.google.com/analytics/bigquery/export-schema" (sourceResource first_)+      assertEqual (Just "GA4 BigQuery Export schema") (sourceTitle first_)+      -- `author` uses the section 7 actor convention; `team:ga4-docs` matches+      -- none of the three shapes, so it stays unclassified rather than failing.+      assertEqual (Just (UnclassifiedActor "team:ga4-docs")) (sourceAuthor first_)+      assertEqual (Just 5000) (sourceUsageCount first_)+      assertEqual (Just "2026-05-30") (sourceLastModified first_)+    [] -> Left "expected sources"+  -- Section 5.1 permits a resource to be a population or scope descriptor no+  -- consumer can follow. It must read cleanly and never be treated as a path.+  assertEqual+    (Just "all queries in BigQuery project X")+    (sourceResource <$> List.find ((== Just "broad-scope") . sourceId) sources)+  -- A numeric string is not an integer. Reading it as one would make the+  -- field's type unpredictable and hide a producer mistake.+  assertEqual+    (Just Nothing)+    (sourceUsageCount <$> List.find ((== Just "broad-scope") . sourceId) sources)+  absent <- firstShow (parseDocument "---\ntype: Recipe\n---\nBody\n")+  assertEqual [] (readSources (absent ^. #frontmatter))++testUsageWindowOverride :: Either Text ()+testUsageWindowOverride = do+  document <- firstShow (parseDocument sourcesFixtureDocument)+  let documentWindow = readUsageWindow (document ^. #frontmatter)+      sources = readSources (document ^. #frontmatter)+      windowFor entryId =+        effectiveUsageWindow documentWindow <$> List.find ((== Just entryId) . sourceId) sources+  assertEqual (Just (UsageWindow (Just "2026-06-01") (Just "2026-06-30"))) documentWindow+  -- An entry with no window of its own inherits the document-scope one...+  assertEqual (Just (Just (UsageWindow (Just "2026-06-01") (Just "2026-06-30")))) (windowFor "ga4-schema")+  -- ...and an entry carrying its own overrides it. Two different windows in one+  -- document is the section 5.1 override rule working.+  assertEqual (Just (Just (UsageWindow (Just "2026-01-01") (Just "2026-01-31")))) (windowFor "exec-dash")+  -- With no window at either scope there is nothing to frame a count with.+  noWindow <- firstShow (parseDocument "---\ntype: Recipe\nsources:\n  - resource: https://example.com/a\n---\nBody\n")+  let noWindowSources = readSources (noWindow ^. #frontmatter)+  assertEqual Nothing (readUsageWindow (noWindow ^. #frontmatter))+  assertEqual [Nothing] (effectiveUsageWindow Nothing <$> noWindowSources)++testSourcesRoundTrip :: Either Text ()+testSourcesRoundTrip = do+  let sources =+        [ Source+            { sourceId = Just "ga4-schema",+              sourceResource = "https://developers.google.com/analytics/bigquery/export-schema",+              sourceTitle = Just "GA4 BigQuery Export schema",+              sourceAuthor = Just (parseActor "human:ahormati"),+              sourceUsageCount = Just 5000,+              sourceLastModified = Just "2026-05-30",+              sourceUsageWindow = Nothing+            },+          -- Every optional key absent: these must be omitted on write, not+          -- written as explicit nulls, so the round-trip is lossless.+          Source+            { sourceId = Nothing,+              sourceResource = "all queries in BigQuery project X",+              sourceTitle = Nothing,+              sourceAuthor = Nothing,+              sourceUsageCount = Nothing,+              sourceLastModified = Nothing,+              sourceUsageWindow = Just (UsageWindow (Just "2026-01-01") Nothing)+            }+        ]+      window = UsageWindow (Just "2026-06-01") (Just "2026-06-30")+      built = setUsageWindow window (setSources sources (setType "BigQuery Table" emptyFrontmatter))+  reparsed <- firstShow (parseDocument (serializeDocument (OKFDocument built "# Orders\n")))+  assertEqual sources (readSources (reparsed ^. #frontmatter))+  assertEqual (Just window) (readUsageWindow (reparsed ^. #frontmatter))++-- | Specification §10.2's worked example, verbatim. Flow-style mappings and a+-- flow-style @receipt@ list are exactly how the specification writes it, which+-- is why they are here: a reader that only handles block style would pass a+-- hand-normalized fixture and fail on the document an author copied out of §10.+attestedComputationFixtureDocument :: Text+attestedComputationFixtureDocument =+  Text.unlines+    [ "---",+      "type: Attested Computation",+      "title: Revenue for fiscal year",+      "description: Recognized revenue for a fiscal year, per Finance's definition.",+      "status: stable",+      "runtime: bigquery",+      "parameters:",+      "  - { name: year, type: integer, required: true }",+      "executor:",+      "  resource: references/skills/run-on-bq.md",+      "  receipt: [job_id, executed_sql, result]",+      "attester:",+      "  resource: references/attesters/revenue.py",+      "generated: { by: reference_agent/gemini-2.5-pro, at: 2026-06-20T22:53:05Z }",+      "verified: { by: human:ahormati, at: 2026-06-25T09:00:00Z }",+      "stale_after: 2026-09-23",+      "sources:",+      "  - id: rev-policy",+      "    resource: https://wiki.acme/finance/revenue-recognition",+      "    title: Revenue recognition policy",+      "---",+      "",+      "# Computation",+      "",+      "    SELECT SUM(amount) AS revenue FROM finance.recognized_revenue WHERE fiscal_year = @year"+    ]++-- | The five §10.2 contract fields read off the specification's own worked+-- example. The trust and provenance families in the same frontmatter block are+-- asserted too: §10.2 puts them there deliberately, and reading the contract+-- must not disturb them.+testReadAttestedComputationContract :: Either Text ()+testReadAttestedComputationContract = do+  document <- firstShow (parseDocument attestedComputationFixtureDocument)+  let frontmatterValue = document ^. #frontmatter+  assertEqual (Just "bigquery") (readRuntime frontmatterValue)+  assertEqual+    [Parameter {parameterName = "year", parameterType = Just "integer", parameterRequired = Just True}]+    (readParameters frontmatterValue)+  -- Absent: §10.3 says an absent `computation` means the body fence is the+  -- computation. Reading the body is a sibling plan's job.+  assertEqual Nothing (readComputation frontmatterValue)+  assertEqual+    ( Just+        Executor+          { executorResource = Just "references/skills/run-on-bq.md",+            executorReceipt = ["job_id", "executed_sql", "result"]+          }+    )+    (readExecutor frontmatterValue)+  assertEqual (Just (Attester (Just "references/attesters/revenue.py"))) (readAttester frontmatterValue)+  -- The §5 families sharing the block still read exactly as before.+  assertEqual+    (Just (Generated (parseActor "reference_agent/gemini-2.5-pro") (Just "2026-06-20T22:53:05Z")))+    (readGenerated frontmatterValue)+  assertEqual [Verification (parseActor "human:ahormati") (Just "2026-06-25T09:00:00Z")] (readVerified frontmatterValue)+  assertEqual Stable (readStatus frontmatterValue)+  assertEqual (Just "2026-09-23") (readStaleAfter frontmatterValue)+  assertEqual [Just "rev-policy"] (map sourceId (readSources frontmatterValue))++-- | Every degenerate contract shape yields a value rather than an error.+-- Specification §11 forbids rejecting a document for a malformed optional+-- field, so the readers are total and reporting is validation's job.+testReadAttestedComputationDegenerateShapes :: Either Text ()+testReadAttestedComputationDegenerateShapes = do+  let readAll source = do+        document <- firstShow (parseDocument source)+        pure (document ^. #frontmatter)+  -- Nothing declared at all.+  bare <- readAll "---\ntype: Attested Computation\n---\nBody\n"+  assertEqual Nothing (readRuntime bare)+  assertEqual [] (readParameters bare)+  assertEqual Nothing (readComputation bare)+  assertEqual Nothing (readExecutor bare)+  assertEqual Nothing (readAttester bare)+  -- `parameters` present but not a list, and `runtime` present but not text.+  wrongShapes <-+    readAll+      ( Text.unlines+          [ "---",+            "type: Attested Computation",+            "runtime: { name: bigquery }",+            "parameters: year",+            "computation: [a, b]",+            "---",+            "Body"+          ]+      )+  assertEqual Nothing (readRuntime wrongShapes)+  assertEqual [] (readParameters wrongShapes)+  assertEqual Nothing (readComputation wrongShapes)+  -- An entry with no `name` names no hole and is dropped, exactly as+  -- `readSources` drops an entry with no `resource`. A `required` written as a+  -- string is not a boolean, mirroring `usage_count`'s refusal of "5000".+  partialEntries <-+    readAll+      ( Text.unlines+          [ "---",+            "type: Attested Computation",+            "parameters:",+            "  - { type: integer, required: true }",+            "  - { name: year }",+            "  - { name: region, type: string, required: \"true\" }",+            "  - not-a-mapping",+            "---",+            "Body"+          ]+      )+  assertEqual+    [ Parameter {parameterName = "year", parameterType = Nothing, parameterRequired = Nothing},+      Parameter {parameterName = "region", parameterType = Just "string", parameterRequired = Nothing}+    ]+    (readParameters partialEntries)+  -- `executor` as a scalar is not a mapping and is not read; a `receipt`+  -- written as a bare string is read as a one-element list, mirroring how §5.2+  -- tolerates a bare `verified` mapping where a list is expected.+  scalarExecutor <- readAll "---\ntype: Attested Computation\nexecutor: run-on-bq\nattester: revenue.py\n---\nBody\n"+  assertEqual Nothing (readExecutor scalarExecutor)+  assertEqual Nothing (readAttester scalarExecutor)+  bareReceipt <-+    readAll+      ( Text.unlines+          [ "---",+            "type: Attested Computation",+            "executor: { receipt: job_id }",+            "attester: { note: no resource here }",+            "---",+            "Body"+          ]+      )+  assertEqual+    (Just Executor {executorResource = Nothing, executorReceipt = ["job_id"]})+    (readExecutor bareReceipt)+  -- An `attester` mapping with no `resource` still reads: "declared badly" and+  -- "not declared" are different facts and only the reader can keep them apart.+  assertEqual (Just (Attester Nothing)) (readAttester bareReceipt)++-- | The §10.2 worked example survives serialization losslessly, and the+-- normalized form emits the five contract keys in their fixed+-- 'coreFrontmatterFieldOrder' position — between the lifecycle @status@ and the+-- trust @generated@, which is §10.2's own ordering.+--+-- Byte-identity is asserted against the /normalized/ form rather than against+-- the specification's text, because §10.2 writes flow-style mappings that+-- 'serializeDocument' expands to block style by design. What this pins is that+-- serializing is a fixed point: a bundle regenerated twice yields no diff.+testAttestedComputationRoundTrip :: Either Text ()+testAttestedComputationRoundTrip = do+  document <- firstShow (parseDocument attestedComputationFixtureDocument)+  let normalized = serializeDocument document+  reparsed <- firstShow (parseDocument normalized)+  assertEqual normalized (serializeDocument reparsed)+  -- No contract value was normalized away or rewritten on the way through.+  assertEqual (readRuntime (document ^. #frontmatter)) (readRuntime (reparsed ^. #frontmatter))+  assertEqual (readParameters (document ^. #frontmatter)) (readParameters (reparsed ^. #frontmatter))+  assertEqual (readComputation (document ^. #frontmatter)) (readComputation (reparsed ^. #frontmatter))+  assertEqual (readExecutor (document ^. #frontmatter)) (readExecutor (reparsed ^. #frontmatter))+  assertEqual (readAttester (document ^. #frontmatter)) (readAttester (reparsed ^. #frontmatter))+  assertEqual (body document) (body reparsed)+  assertEqual+    [ "type",+      "title",+      "description",+      "status",+      "runtime",+      "parameters",+      "executor",+      "attester",+      "generated",+      "verified",+      "stale_after",+      "sources"+    ]+    (topLevelKeysInEmissionOrder normalized)++-- | §10.3's two forms, read off one document each and then off a document that+-- wrongly offers both. The reader restates and never enforces, so the+-- both-forms document yields two entries rather than a failure; reporting that+-- is 'validateDocument''s job.+testReadComputationSources :: Either Text ()+testReadComputationSources = do+  -- The specification's own worked example: no `computation` key, one indented+  -- block under `# Computation`.+  inline <- firstShow (parseDocument attestedComputationFixtureDocument)+  assertEqual+    [ComputationInline "SELECT SUM(amount) AS revenue FROM finance.recognized_revenue WHERE fiscal_year = @year\n"]+    (readComputationSources inline)+  byFile <-+    firstShow+      ( parseDocument+          ( Text.unlines+              [ "---",+                "type: Attested Computation",+                "computation: /references/revenue.sql",+                "---",+                "",+                "# Notes",+                "",+                "The computation lives in a file, so this body carries no block."+              ]+          )+      )+  assertEqual [ComputationFile "/references/revenue.sql"] (readComputationSources byFile)+  both <-+    firstShow+      ( parseDocument+          ( Text.unlines+              [ "---",+                "type: Attested Computation",+                "computation: /references/revenue.sql",+                "---",+                "",+                "# Computation",+                "",+                "```sql",+                "SELECT 1",+                "```"+              ]+          )+      )+  assertEqual+    [ComputationFile "/references/revenue.sql", ComputationInline "SELECT 1\n"]+    (readComputationSources both)+  -- Type-agnostic: a `# Computation` section on a `Metric` is still a fact about+  -- that document. Scoping a report to the one type is `Okf.Validation`'s job.+  onMetric <-+    firstShow+      ( parseDocument+          (Text.unlines ["---", "type: Metric", "---", "", "# Computation", "", "    SELECT 1"])+      )+  assertEqual [ComputationInline "SELECT 1\n"] (readComputationSources onMetric)++-- | The top-level frontmatter keys of a serialized document, in the order they+-- were emitted. A top-level key is the only thing that starts in column zero+-- inside the frontmatter fence.+topLevelKeysInEmissionOrder :: Text -> [Text]+topLevelKeysInEmissionOrder serialized =+  [ Text.takeWhile (/= ':') line+  | line <- frontmatterLines,+    not (Text.null line),+    Text.isInfixOf ":" line,+    Text.head line /= ' ',+    Text.head line /= '-'+  ]+  where+    frontmatterLines =+      takeWhile (/= "---") (drop 1 (Text.lines serialized))++-- | Specification §10.2 marks @runtime@ REQUIRED for @type: Attested+-- Computation@, and nothing else in the contract. The check is strict-only:+-- §11's conformance list has three items and none is a computation field, and+-- §11 separately forbids rejecting a bundle over an unknown @type@ value, so+-- "REQUIRED for this type" binds the producer rather than licensing a consumer+-- to refuse.+testValidateAttestedComputationRuntime :: Either Text ()+testValidateAttestedComputationRuntime = do+  let errorsFor profile source = validateDocument profile <$> firstShow (parseDocument source)+      concept typeValue extraLines =+        Text.unlines+          ( [ "---",+              "type: " <> typeValue,+              "title: Revenue",+              "description: Recognized revenue for a fiscal year.",+              "generated: { by: human:you, at: 2026-08-01T00:00:00Z }"+            ]+              <> extraLines+              <> ["---", "", "# Computation", "", "    SELECT 1"]+          )+  -- A complete contract is clean under both profiles.+  complete <- errorsFor StrictAuthoring (concept "Attested Computation" ["runtime: bigquery"])+  assertEqual [] complete+  -- No runtime: exactly one problem, and only under strict.+  missing <- errorsFor StrictAuthoring (concept "Attested Computation" [])+  assertEqual [AttestedComputationMissingRuntime] missing+  permissive <- errorsFor PermissiveConformance (concept "Attested Computation" [])+  assertEqual [] permissive+  -- No other type is affected, including a near-miss spelling. §4.1 says types+  -- are not registered centrally and consumers must tolerate unknown ones, so+  -- the match is on the one literal §10.1 names, case-sensitively.+  metric <- errorsFor StrictAuthoring (concept "Metric" [])+  assertEqual [] metric+  nearMiss <- errorsFor StrictAuthoring (concept "attested computation" [])+  assertEqual [] nearMiss+  -- An empty or whitespace runtime declares nothing.+  blank <- errorsFor StrictAuthoring (concept "Attested Computation" ["runtime: \"   \""])+  assertEqual [AttestedComputationMissingRuntime] blank++testValidateSources :: Either Text ()+testValidateSources = do+  let strictErrors source = validateDocument StrictAuthoring <$> firstShow (parseDocument source)+      permissiveErrors source = validateDocument PermissiveConformance <$> firstShow (parseDocument source)+      preamble =+        Text.unlines+          [ "---",+            "type: BigQuery Table",+            "title: Orders",+            "description: Order fact table.",+            "generated: { by: human:ahormati, at: 2026-06-20T22:53:05Z }"+          ]+      broken =+        preamble+          <> Text.unlines+            [ "sources:",+              "  - id: ga4-schema",+              "    resource: https://example.com/ga4",+              "  - id: no-resource",+              "    title: Missing the required key",+              "  - id: ga4-schema",+              "    resource: https://example.com/ga4-again",+              "---",+              "",+              "# Orders"+            ]+  errors <- strictErrors broken+  -- The index is the position in the raw YAML list, which is what a person sees+  -- in the file, not the position in the list readSources returns.+  assertEqual [SourceMissingResource 1, DuplicateSourceId "ga4-schema"] errors+  -- Section 11 forbids rejecting a bundle over an optional family, so neither+  -- diagnostic may fire permissively.+  permissive <- permissiveErrors broken+  assertEqual [] permissive+  -- A well-formed sources list, including a scope-descriptor resource that no+  -- consumer can follow, is clean. Section 5.1 explicitly permits that shape.+  clean <-+    strictErrors+      ( preamble+          <> Text.unlines+            [ "sources:",+              "  - id: ga4-schema",+              "    resource: https://example.com/ga4",+              "  - resource: all queries in BigQuery project X",+              "---",+              "",+              "# Orders"+            ]+      )+  assertEqual [] clean+  -- A document with no sources at all stays valid in strict mode.+  noSources <- strictErrors (preamble <> "---\n\n# Orders\n")+  assertEqual [] noSources++testConceptFromDocumentDerivesFields :: Either Text ()+testConceptFromDocumentDerivesFields = do+  conceptId <- parseTestConceptId "tables/orders"+  let frontmatterValue =+        okfCommon+          OkfCommon+            { commonType = "BigQuery Table",+              commonTitle = Just "Orders",+              commonDescription = Nothing,+              commonTimestamp = Nothing+            }+      concept = conceptFromDocument conceptId (OKFDocument frontmatterValue "# Orders\n")+  assertEqual "BigQuery Table" (conceptType concept)+  assertEqual (Just "Orders") (conceptTitle concept)+  assertEqual "tables/orders.md" (conceptSourcePath concept)++testWriteBundleRoundTrip :: IO (Either Text ())+testWriteBundleRoundTrip = do+  temporaryDirectory <- getTemporaryDirectory+  root <- createTempDirectory temporaryDirectory "okf-core-writebundle"+  let buildConcepts = do+        orders <- testConcept "tables/orders" "# Orders\n\nOrder records.\n"+        customers <- testConcept "tables/customers" "# Customers\n\nCustomer records.\n"+        pure [orders, customers]+  case buildConcepts of+    Left message -> do+      removeDirectoryRecursive root+      pure (Left message)+    Right concepts -> do+      writeBundle root concepts+      recovered <- readBundle root+      removeDirectoryRecursive root+      pure+        ( do+            assertEqual+              (List.sort (renderConceptId . conceptIdOf <$> concepts))+              (List.sort (renderConceptId . conceptIdOf <$> recovered))+            assertEqual+              (List.sort ((body . conceptDocument) <$> concepts))+              (List.sort ((body . conceptDocument) <$> recovered))+        )++testFixtureDanglingLink :: IO (Either Text ())+testFixtureDanglingLink = do+  root <- fixturePath "invalid-dangling-link"+  concepts <- readBundle root+  inventory <- readBundleInventory root+  pure+    ( case validateBundle PermissiveConformance VersionUndeclared inventory concepts of+        errs+          | any isDangling errs -> Right ()+          | otherwise -> Left ("expected a DanglingReference, got: " <> Text.pack (show errs))+    )+  where+    isDangling DanglingReference {} = True+    isDangling _ = False++-- | The §6.2 path check against a real directory rather than an in-memory+-- bundle, which is the only way to exercise the half that needs a filesystem:+-- @non-markdown.md@ names @references\/attesters\/revenue.py@, and that resolves+-- only because 'walkBundleInventory' sees files 'walkBundle' filters out.+--+-- @computations\/spec-spelling.md@ is the same text written from a+-- subdirectory, which is specification §10.2's own spelling and the one shape+-- that carries a bundle-relative hint.+testFixtureDanglingFrontmatterPath :: IO (Either Text ())+testFixtureDanglingFrontmatterPath = do+  root <- fixturePath "dangling-frontmatter-path"+  concepts <- readBundle root+  inventory <- readBundleInventory root+  pure+    ( do+        danglingId <- firstShow (parseConceptId "dangling")+        specSpellingId <- firstShow (parseConceptId "computations/spec-spelling")+        assertEqual 4 (length concepts)+        assertEqual+          [ DanglingFrontmatterPath+              specSpellingId+              "resource"+              "computations/references/attesters/revenue.py"+              (Just "references/attesters/revenue.py"),+            DanglingFrontmatterPath danglingId "resource" "references/deleted.txt" Nothing+          ]+          (validateBundle StrictAuthoring (VersionDeclared (OkfVersion 0 2)) inventory concepts)+        assertEqual+          []+          (validateBundle PermissiveConformance (VersionDeclared (OkfVersion 0 2)) inventory concepts)+    )++-- | A whole bundle carrying specification §10.2's contract and §10.3's+-- exactly-one rule, checked end to end.+--+-- Four things this proves that the document-level tests cannot. The §10.2 and+-- §10.3 checks fire on exactly the concepts that get them wrong and leave the+-- @Metric@ and the @references\/@ concept alone — @metrics\/revenue@+-- carries no computation at all and is reported by none of them, which is what+-- proves the checks are keyed on the one @type@. Both of the completed+-- computation's path-valued contract fields resolve, including the non-Markdown+-- @revenue.py@ — which only works because 'walkBundleInventory' records every+-- file rather than only the concepts. @computations\/both-computations@ names a+-- @computation@ path that resolves, so its only diagnostic is the §10.3+-- ambiguity and not a dangling path. And permissive validation reports nothing+-- at all, because §11's conformance list reaches none of this.+testFixtureAttestedComputation :: IO (Either Text ())+testFixtureAttestedComputation = do+  root <- fixturePath "attested-computation"+  concepts <- readBundle root+  inventory <- readBundleInventory root+  pure+    ( do+        marginId <- firstShow (parseConceptId "computations/margin")+        revenueId <- firstShow (parseConceptId "computations/revenue")+        bothId <- firstShow (parseConceptId "computations/both-computations")+        noneId <- firstShow (parseConceptId "computations/no-computation")+        twoBlocksId <- firstShow (parseConceptId "computations/two-blocks")+        -- Six computations, one metric, and the one `references/` file that+        -- `walkBundle` treats as a concept because it is non-reserved Markdown.+        -- The `.py` and `.sql` under `references/` are files and not concepts.+        --+        -- The sixth computation, `computations/churn`, deliberately produces no+        -- diagnostic here. It is core-clean and deviates only from the house+        -- profile in `profiles/attested-computation-house.dhall`, which is what+        -- makes this bundle exercise both layers rather than only this one.+        assertEqual 8 (length concepts)+        assertEqual+          [ DocumentInvalid bothId AttestedComputationHasBothComputations,+            DocumentInvalid marginId AttestedComputationMissingRuntime,+            DocumentInvalid noneId AttestedComputationHasNoComputation,+            DocumentInvalid twoBlocksId (AttestedComputationHasManyBlocks 2)+          ]+          (validateBundle StrictAuthoring (VersionDeclared (OkfVersion 0 2)) inventory concepts)+        assertEqual+          []+          (validateBundle PermissiveConformance (VersionDeclared (OkfVersion 0 2)) inventory concepts)+        -- The contract projected onto the concept, which is what every command+        -- reads rather than reaching back into raw frontmatter.+        revenue <- maybe (Left "expected computations/revenue") Right (findConcept revenueId concepts)+        assertEqual (Just "bigquery") (conceptRuntime revenue)+        assertEqual ["year"] (parameterName <$> conceptParameters revenue)+        assertEqual Nothing (conceptComputation revenue)+        assertEqual+          (Just "/references/skills/run-on-bq.md")+          (executorResource =<< conceptExecutor revenue)+        assertEqual (Just ["job_id", "executed_sql", "result"]) (executorReceipt <$> conceptExecutor revenue)+        assertEqual (Just "/references/attesters/revenue.py") (attesterResource =<< conceptAttester revenue)+        -- The body half of §10.3, projected alongside the frontmatter half: this+        -- concept names no `computation` path, so its one computation is the+        -- indented block under `# Computation`.+        assertEqual+          [ ComputationInline+              "SELECT SUM(amount) AS revenue\nFROM finance.recognized_revenue\nWHERE fiscal_year = @year\n"+          ]+          (conceptComputationSources revenue)+    )++-- | Resolve a fixture file path regardless of whether tests run from the repo+-- root or the package directory (mirrors 'fixturePath' for files).+fixtureFilePath :: FilePath -> IO FilePath+fixtureFilePath name = findExisting candidates+  where+    candidates =+      [ "okf-core" </> "test" </> "fixtures" </> name,+        "test" </> "fixtures" </> name+      ]+    findExisting [] = fail ("fixture file not found: " <> name)+    findExisting (candidate : rest) = do+      exists <- doesFileExist candidate+      if exists then pure candidate else findExisting rest++-- | Milestone 1: the Dhall descriptor round-trips into a 'ProfileSpec'.+testLoadProfileFixture :: IO (Either Text ())+testLoadProfileFixture = do+  path <- fixtureFilePath "profiles/postgresql.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load profile: " <> err)+    Right spec -> do+      assertEqual "shinzui-postgresql" (spec ^. #name)+      assertEqual+        (Just "Conventions for documenting a PostgreSQL database as an OKF bundle.")+        (spec ^. #description)+      assertEqual False (spec ^. #allowUnknownTypes)+      assertEqual ["type", "title"] (map (^. #field) (spec ^. #frontmatter . #required))+      assertEqual+        [ Just "The OKF concept type; must be one of the type rules below.",+          Just "Human-readable name of the object, as a reader would say it."+        ]+        (map (^. #description) (spec ^. #frontmatter . #required))+      -- `timestamp` is written with bare record completion, so it carries no prose.+      assertEqual+        [ Just "One or two sentences on what this object is for.",+          Nothing,+          Just "postgresql:// URI locating the live object."+        ]+        (map (^. #description) (spec ^. #frontmatter . #recommended))+      assertEqual+        ["PostgreSQL Schema", "PostgreSQL Table", "PostgreSQL View"]+        (map (^. #type_) (spec ^. #types))+      assertEqual+        (Just "One physical table in a schema, including its column list.")+        (spec ^. #types . to (!! 1) . #description)++testLoadDocumentIdProfileFixture :: IO (Either Text ())+testLoadDocumentIdProfileFixture = do+  path <- fixtureFilePath "profiles/decisions.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load document ID profile: " <> err)+    Right spec -> do+      assertEqual (Just "docId") (spec ^. #idField)+      assertEqual [Just "ADR"] (map (^. #idPrefix) (spec ^. #types))+      -- Written with the mk/FieldRule.dhall constructors, which normalize to+      -- exactly what record completion produces.+      assertEqual ["type", "title"] (map (^. #field) (spec ^. #frontmatter . #required))+      assertEqual+        [Just "The OKF concept type; must be a type rule below.", Nothing]+        (map (^. #description) (spec ^. #frontmatter . #required))++testLoadNestedReferenceProfileFixture :: IO (Either Text ())+testLoadNestedReferenceProfileFixture = do+  path <- fixtureFilePath "profiles/nested-references-and-uniqueness.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load nested reference profile: " <> err)+    Right spec -> do+      dependencies <- lookupRawRule "dependencies" (spec ^. #frontmatter . #required)+      acceptanceCriteria <- lookupRawRule "acceptanceCriteria" (spec ^. #frontmatter . #required)+      assertEqual (Just "id") (acceptanceCriteria ^. #uniqueBy)+      case dependencies ^. #elementFields of+        Just NestedRules {presenceConstraints = [], timestampOrderConstraints = [], required = [nestedReferenceRule]} -> do+          let expectedPolicy =+                HandleReferenceRule+                  "IR"+                  ["mori"]+                  False+                  False+                  (Just "mori://[^/]+/[^/]+/okf/improvement-requests/concepts/IR-[1-9][0-9]*")+          assertEqual (Just expectedPolicy) (nestedReferenceRule ^. #reference)+          assertEqual+            ( object+                [ "field" .= ("ref" :: Text),+                  "description" .= (Nothing :: Maybe Text),+                  "allowedValues" .= ([] :: [Text]),+                  "cardinality" .= ("scalar" :: Text),+                  "format" .= (Nothing :: Maybe Text),+                  "when" .= (Nothing :: Maybe FieldCondition),+                  "path" .= (Nothing :: Maybe PathReferenceRule),+                  "reference" .= Just expectedPolicy+                ]+            )+            (toJSON nestedReferenceRule)+        _ -> Left "expected dependencies.ref as one required nested rule"+  where+    lookupRawRule key rules =+      case [rule | rule <- rules, rule ^. #field == key] of+        [rule] -> Right rule+        _ -> Left ("expected one raw rule for " <> key)++testLoadDescribedProfileFixture :: IO (Either Text ())+testLoadDescribedProfileFixture = do+  path <- fixtureFilePath "profiles/described.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load described profile: " <> err)+    Right spec -> do+      assertEqual "described" (spec ^. #name)+      assertEqual ["Described Concept"] (map (^. #type_) (spec ^. #types))+      assertEqual [emptyTestFrontmatterRules] (map (^. #frontmatter) (spec ^. #types))+      assertEqual True (spec ^. #allowUnknownFields)+      assertEqual [[]] (map (^. #allowedValues) (spec ^. #frontmatter . #required))+      assertEqual [Any] (map (^. #cardinality) (spec ^. #frontmatter . #required))++testLoadTypeAwareCompatibilityFixture :: IO (Either Text ())+testLoadTypeAwareCompatibilityFixture = do+  path <- fixtureFilePath "profiles/type-aware-ep1.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load EP-1 profile: " <> err)+    Right spec -> do+      assertEqual "type-aware-ep1" (spec ^. #name)+      assertEqual True (spec ^. #allowUnknownFields)+      assertEqual [[]] (map (^. #allowedValues) (spec ^. #frontmatter . #required))+      assertEqual [[[]]] (map (map (^. #allowedValues) . (^. #frontmatter . #required)) (spec ^. #types))+      assertEqual [Any] (map (^. #cardinality) (spec ^. #frontmatter . #required))++testLoadVocabularyCompatibilityFixture :: IO (Either Text ())+testLoadVocabularyCompatibilityFixture = do+  path <- fixtureFilePath "profiles/vocabulary-ep2.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load EP-2 profile: " <> err)+    Right spec -> do+      assertEqual "vocabulary-ep2" (spec ^. #name)+      assertEqual False (spec ^. #allowUnknownFields)+      assertEqual [[], ["draft", "accepted"]] (map (^. #allowedValues) (spec ^. #frontmatter . #required))+      assertEqual [Any, Any] (map (^. #cardinality) (spec ^. #frontmatter . #required))+      assertEqual [Nothing, Nothing] (map (^. #format) (spec ^. #frontmatter . #required))++testLoadCardinalityCompatibilityFixture :: IO (Either Text ())+testLoadCardinalityCompatibilityFixture = do+  path <- fixtureFilePath "profiles/cardinality-ep3.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load EP-3 profile: " <> err)+    Right spec -> do+      assertEqual "cardinality-ep3" (spec ^. #name)+      assertEqual False (spec ^. #allowUnknownFields)+      assertEqual [Any, Scalar] (map (^. #cardinality) (spec ^. #frontmatter . #required))+      assertEqual [Nothing, Nothing] (map (^. #format) (spec ^. #frontmatter . #required))++testLoadFormatCompatibilityFixture :: IO (Either Text ())+testLoadFormatCompatibilityFixture = do+  path <- fixtureFilePath "profiles/formats-ep4.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load EP-4 profile: " <> err)+    Right spec -> do+      assertEqual "formats-ep4" (spec ^. #name)+      assertEqual [Any, Scalar] (map (^. #cardinality) (spec ^. #frontmatter . #required))+      assertEqual [Nothing, Just Rfc3339Utc] (map (^. #format) (spec ^. #frontmatter . #required))+      assertEqual [Nothing, Nothing] (map (^. #elementFields) (spec ^. #frontmatter . #required))++testLoadNestedReviewsProfileFixture :: IO (Either Text ())+testLoadNestedReviewsProfileFixture = do+  path <- fixtureFilePath "profiles/nested-reviews.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load nested review profile: " <> err)+    Right spec ->+      case [rules | rule <- spec ^. #frontmatter . #required, rule ^. #field == "reviews", Just rules <- [rule ^. #elementFields]] of+        [NestedRules {required, recommended}] -> do+          assertEqual ["kind", "reviewer", "reviewed_at", "document_timestamp", "scope", "outcome", "context"] (map (^. #field) required)+          assertEqual ["notes"] (map (^. #field) recommended)+        _ -> Left "expected exactly one reviews rule with elementFields"++testLoadNestedCompatibilityFixture :: IO (Either Text ())+testLoadNestedCompatibilityFixture = do+  path <- fixtureFilePath "profiles/nested-reviews-ep1.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load frozen nested profile: " <> err)+    Right spec ->+      case spec ^. #frontmatter . #required of+        [rule] -> do+          assertEqual Nothing (rule ^. #when)+          case rule ^. #elementFields of+            Just NestedRules {presenceConstraints = [], timestampOrderConstraints = [], required = [nestedRule]} -> do+              assertEqual "kind" (nestedRule ^. #field)+              assertEqual Nothing (nestedRule ^. #when)+            _ -> Left "expected the frozen nested rule to survive the compatibility upgrade"+        _ -> Left "expected one frozen top-level rule"++testLoadConditionalFieldsProfileFixture :: IO (Either Text ())+testLoadConditionalFieldsProfileFixture = do+  path <- fixtureFilePath "profiles/conditional-fields.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load conditional profile: " <> err)+    Right spec -> do+      assertEqual "conditional-fields" (spec ^. #name)+      compiled <- firstShow (compileProfile spec)+      assertEqual spec (compiledProfileSpec compiled)++testLoadConditionalCompatibilityFixture :: IO (Either Text ())+testLoadConditionalCompatibilityFixture = do+  path <- fixtureFilePath "profiles/conditional-fields-ep2.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load frozen condition-aware profile: " <> err)+    Right spec ->+      case spec ^. #frontmatter . #required of+        [sourceRule, targetRule, reviewsRule] -> do+          assertEqual Nothing (sourceRule ^. #reference)+          assertEqual (Just (FieldCondition "status" ["superseded"])) (targetRule ^. #when)+          assertEqual Nothing (targetRule ^. #reference)+          case reviewsRule ^. #elementFields of+            Just NestedRules {presenceConstraints = [], timestampOrderConstraints = [], required = [_kindRule, providerRule]} ->+              assertEqual (Just (FieldCondition "kind" ["model"])) (providerRule ^. #when)+            _ -> Left "expected frozen nested conditions to survive the compatibility upgrade"+        _ -> Left "expected three frozen condition-aware top-level rules"++-- | The immediately preceding generation: a descriptor that spells out the+-- reference-aware record types with no @optional@ list anywhere still loads,+-- keeps every field it did declare, and behaves as though each optional list+-- were empty.+testLoadReferenceCompatibilityFixture :: IO (Either Text ())+testLoadReferenceCompatibilityFixture = do+  path <- fixtureFilePath "profiles/document-references-ep3.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load frozen reference-aware profile: " <> err)+    Right spec -> do+      assertEqual [] (spec ^. #frontmatter . #optional)+      assertEqual [[]] (map (^. #frontmatter . #optional) (spec ^. #types))+      case spec ^. #frontmatter . #recommended of+        [referenceRule, conditionRule, reviewsRule] -> do+          assertEqual+            (Just (handleReferenceRule "ADR" ["mori"] False))+            (referenceRule ^. #reference)+          assertEqual (Just (FieldCondition "status" ["superseded"])) (conditionRule ^. #when)+          case reviewsRule ^. #elementFields of+            Just NestedRules {presenceConstraints = [], timestampOrderConstraints = [], required = [kindRule], recommended = [notesRule], optional = nestedOptional} -> do+              assertEqual "kind" (kindRule ^. #field)+              assertEqual "notes" (notesRule ^. #field)+              assertEqual [] (map (^. #field) nestedOptional)+            _ -> Left "expected the frozen nested rules to survive with an empty optional list"+        _ -> Left "expected three frozen reference-aware recommended rules"++-- | Every frozen generation fixture must both decode /and/ compile.+--+-- Decoding alone is the weaker property and was, until this test, the only one+-- asserted: eight of the nine generation tests stopped at 'loadProfileFile'. But+-- the guarantee the frozen chain exists to provide is that a descriptor pinned+-- at any released version keeps /working/, and between decoding and working sits+-- 'compileProfile' — where every 'ProfileDefinitionError' is a way for a+-- descriptor that decoded perfectly to stop working.+--+-- The gap was not theoretical. A compile-time version check written for this+-- plan rejected ten fixtures at once, and the failures surfaced in unrelated+-- documentation and optional-field tests rather than here, which is a far worse+-- signal. It also let @path-references-mp8-ep3.dhall@ ship in a state where it+-- decoded and could never compile. See+-- @docs\/adr\/11-growing-the-profile-descriptor-language.md@.+testFrozenFixturesCompile :: IO (Either Text ())+testFrozenFixturesCompile = do+  results <- traverse loadAndCompile frozenGenerationFixtures+  pure (sequence_ results)+  where+    loadAndCompile name = do+      path <- fixtureFilePath ("profiles/" <> name)+      result <- loadProfileFile path+      pure $ case result of+        Left err -> Left (Text.pack name <> " failed to load: " <> err)+        Right spec ->+          case compileProfile spec of+            Left definitionErrors ->+              Left (Text.pack name <> " loads but does not compile: " <> Text.pack (show (toList definitionErrors)))+            Right _ -> Right ()++-- | The fixtures that stand for a released descriptor generation, and so must+-- represent something a real pinned descriptor could be.+--+-- The @*-invalid.dhall@ fixtures are deliberately excluded: they exist to prove+-- a definition error fires. @document-references-ep3.dhall@ is excluded for a+-- different and less happy reason — it declares a profile-scope @when@ condition+-- on @status@ while declaring @status@ only at type scope, so it decodes and has+-- never compiled. That is the same latent defect this test exists to prevent,+-- predating it, and repairing it means changing which rules the fixture declares,+-- which its own test asserts. It is recorded in+-- @docs\/plans\/47-enforce-the-profile-declared-okfversion-and-ship-a-v0-2-reference-profile.md@+-- rather than fixed speculatively here.+frozenGenerationFixtures :: [FilePath]+frozenGenerationFixtures =+  [ "legacy-0.2.dhall",+    "described.dhall",+    "type-aware-ep1.dhall",+    "vocabulary-ep2.dhall",+    "cardinality-ep3.dhall",+    "formats-ep4.dhall",+    "nested-reviews-ep1.dhall",+    "conditional-fields-ep2.dhall",+    "object-fields-mp8-ep1.dhall",+    "formats-mp8-ep2.dhall",+    "path-references-mp8-ep3.dhall",+    "pre-bundle-version.dhall",+    "pre-nested-references-and-uniqueness-0.7.0.0.dhall",+    "pre-guidance-0.8.0.0.dhall",+    "pre-product-discovery-0.10.0.0.dhall",+    "pre-nested-closure.dhall",+    -- Not a frozen generation but a *documented* one: this is the descriptor+    -- @docs\/user\/profiles.md@ shows for the specification §10 contract as a+    -- house convention. It is listed here so the documented descriptor cannot+    -- rot into something that no longer compiles.+    "attested-computation-house.dhall"+  ]++-- | The complete okf-core 0.8.0.0 descriptor generation predates guidance.+-- Both explicit file loading and registry enumeration must reach the same newest+-- frozen decoder, preserve every old value, attach absent guidance at both+-- scopes, and leave the upgraded profile compilable.+testLoadPreGuidanceCompatibilityFixture :: IO (Either Text ())+testLoadPreGuidanceCompatibilityFixture = do+  path <- fixtureFilePath "profiles/pre-guidance-0.8.0.0.dhall"+  loaded <- loadProfileFile path+  registered <- loadRegistry (RegistryFile path)+  pure $ do+    spec <- first ("failed to load frozen pre-guidance profile: " <>) loaded+    assertEqual "pre-guidance-0.8.0.0" (spec ^. #name)+    assertEqual (Just "The complete public 0.8.0.0 descriptor shape.") (spec ^. #description)+    assertEqual Nothing (spec ^. #guidance)+    assertEqual "0.2" (spec ^. #okfVersion)+    assertEqual False (spec ^. #allowUnknownTypes)+    assertEqual True (spec ^. #allowUnknownFields)+    assertEqual (Just "docId") (spec ^. #idField)+    assertEqual (Just "0.2") (spec ^. #requireBundleVersion)+    assertEqual ["type", "dependencies", "generated"] (map (^. #field) (spec ^. #frontmatter . #required))+    assertEqual [Just Profile.NonNegativeInteger] (map (^. #format) (spec ^. #frontmatter . #recommended))+    assertEqual [Just "METRIC"] (map (^. #idPrefix) (spec ^. #types))+    assertEqual [Nothing] (map (^. #guidance) (spec ^. #types))+    case spec ^. #frontmatter . #required of+      [_typeRule, dependenciesRule, generatedRule] -> do+        assertEqual (Just "id") (dependenciesRule ^. #uniqueBy)+        case dependenciesRule ^. #elementFields of+          Just NestedRules {optional = [refRule]} ->+            assertEqual+              (Just (HandleReferenceRule "METRIC" ["mori"] False False (Just "mori://shinzui/.+")))+              (refRule ^. #reference)+          _ -> Left "expected the frozen nested reference rule to survive"+        case generatedRule ^. #objectFields of+          Just NestedRules {presenceConstraints = [], timestampOrderConstraints = [], required = [_byRule, atRule]} ->+            assertEqual (Just Rfc3339Utc) (atRule ^. #format)+          _ -> Left "expected the frozen object rules to survive"+      _ -> Left "expected three frozen required rules"+    _ <- first (Text.pack . show . toList) (compileProfile spec)+    entries <- first ("failed to enumerate frozen pre-guidance profile: " <>) registered+    assertEqual [""] (map (^. #export) entries)+    assertEqual ["pre-guidance-0.8.0.0"] (map (^. #spec . #name) entries)+    assertEqual [Nothing] (map (^. #spec . #guidance) entries)+    registrySpec <- case entries of+      [entry] -> Right (entry ^. #spec)+      _ -> Left "expected exactly one frozen pre-guidance registry entry"+    assertEqual+      [Just "id"]+      [ rule ^. #uniqueBy+      | rule <- registrySpec ^. #frontmatter . #required,+        rule ^. #field == "dependencies"+      ]+    case [ nestedRule ^. #reference+         | rule <- registrySpec ^. #frontmatter . #required,+           rule ^. #field == "dependencies",+           rules <- maybeToList (rule ^. #elementFields),+           nestedRule <- rules ^. #optional+         ] of+      [Just policy] -> assertEqual False (policy ^. #allowLocal)+      _ -> Left "expected registry decoding to preserve the nested reference policy"++-- | Guidance is free-form authoring prose, so decoding and JSON must preserve+-- line breaks rather than folding it into a single display line. The Dhall+-- multiline syntax contributes a final newline; that byte is part of the value+-- and therefore part of this compatibility contract too.+testLoadGuidanceFixture :: IO (Either Text ())+testLoadGuidanceFixture = do+  path <- fixtureFilePath "profiles/guidance.dhall"+  loaded <- loadProfileFile path+  pure $ do+    spec <- first ("failed to load guidance profile: " <>) loaded+    let expectedProfileGuidance =+          "Record the setup, cleanup, and evidence for every run.\n\nKeep supporting checks in source control and make the observed result reproducible.\n"+        expectedTypeGuidance =+          [ "Add a source-controlled Hurl file that exercises the successful response and important failure responses.\n\nRun the Hurl file and retain the useful output as evidence.\n",+            "Exercise the public behavior, then inspect the generated domain-event stream.\n\nVerify event types, payloads, ordering, and stream identity, then verify the externally observable result.\n"+          ]+    assertEqual (Just expectedProfileGuidance) (spec ^. #guidance)+    assertEqual (map Just expectedTypeGuidance) (map (^. #guidance) (spec ^. #types))+    assertJsonGuidance expectedProfileGuidance (toJSON spec)+    for_ (zip expectedTypeGuidance (spec ^. #types)) $ \(expected, rule) ->+      assertJsonGuidance expected (toJSON rule)+  where+    assertJsonGuidance expected = \case+      Aeson.Object fields ->+        assertEqual (Just (Aeson.String expected)) (KeyMap.lookup "guidance" fields)+      _ -> Left "expected profile JSON to be an object"++-- | Guidance is deliberately outside compilation and validation. Removing all+-- guidance from a descriptor must not change either permissive or strict+-- diagnostics for the same concepts.+testGuidanceDoesNotAffectValidation :: IO (Either Text ())+testGuidanceDoesNotAffectValidation = do+  path <- fixtureFilePath "profiles/guidance.dhall"+  loaded <- loadProfileFile path+  let conceptResult = profileConcept "guidance-inert" [] "# Guidance inertness\n"+  pure $ do+    spec <- first ("failed to load guidance profile: " <>) loaded+    concept <- conceptResult+    guided <- firstShow (compileProfile spec)+    let unguidedSpec =+          spec+            & #guidance+            .~ Nothing+            & #types+            %~ map clearTypeGuidance+    unguided <- firstShow (compileProfile unguidedSpec)+    assertEqual+      (validateProfile PermissiveConformance unguided [concept])+      (validateProfile PermissiveConformance guided [concept])+    assertEqual+      (validateProfile StrictAuthoring unguided [concept])+      (validateProfile StrictAuthoring guided [concept])+  where+    clearTypeGuidance :: TypeRule -> TypeRule+    clearTypeGuidance rule = rule & #guidance .~ Nothing++testLoadPreNestedReferenceCompatibilityFixture :: IO (Either Text ())+testLoadPreNestedReferenceCompatibilityFixture = do+  path <- fixtureFilePath "profiles/pre-nested-references-and-uniqueness-0.7.0.0.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load frozen 0.7.0.0 profile: " <> err)+    Right spec -> do+      assertEqual "pre-nested-references-and-uniqueness-0.7.0.0" (spec ^. #name)+      assertEqual (Just "0.2") (spec ^. #requireBundleVersion)+      let allTopRules = spec ^. #frontmatter . #required <> spec ^. #frontmatter . #recommended <> spec ^. #frontmatter . #optional+      assertEqual (replicate (length allTopRules) Nothing) (map (^. #uniqueBy) allTopRules)+      case [policy | rule <- allTopRules, Just policy <- [rule ^. #reference]] of+        [policy] -> do+          assertEqual True (policy ^. #allowLocal)+          assertEqual Nothing (policy ^. #externalUriPattern)+        _ -> Left "expected exactly one upgraded 0.7.0.0 reference policy"+      let nestedRules =+            [ nestedRule+            | rule <- allTopRules,+              rules <- catMaybes [rule ^. #elementFields, rule ^. #objectFields],+              nestedRule <- rules ^. #required <> rules ^. #recommended <> rules ^. #optional+            ]+      assertEqual (replicate (length nestedRules) Nothing) (map (^. #reference) nestedRules)++-- | The generation frozen immediately before @requireBundleVersion@: a descriptor+-- with no such member still loads, the member arrives as 'Nothing', and every+-- member the frozen descriptor did declare survives the upgrade. The last part is+-- what would catch an upgrade function that dropped a field while adding the new+-- one, which is the failure mode a chain this long invites.+testLoadPreBundleVersionCompatibilityFixture :: IO (Either Text ())+testLoadPreBundleVersionCompatibilityFixture = do+  path <- fixtureFilePath "profiles/pre-bundle-version.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load frozen pre-bundle-version profile: " <> err)+    Right spec -> do+      assertEqual "pre-bundle-version" (spec ^. #name)+      -- The new member, absent from the descriptor, means "demand nothing".+      assertEqual Nothing (spec ^. #requireBundleVersion)+      -- Everything else survived: prose, settings, and rules at both scopes.+      assertEqual (Just "Frozen immediately before requireBundleVersion.") (spec ^. #description)+      assertEqual "0.2" (spec ^. #okfVersion)+      assertEqual False (spec ^. #allowUnknownTypes)+      assertEqual True (spec ^. #allowUnknownFields)+      assertEqual (Just "docId") (spec ^. #idField)+      assertEqual ["type", "generated"] (map (^. #field) (spec ^. #frontmatter . #required))+      assertEqual+        (Just (handleReferenceRule "ADR" ["mori"] False))+        (case spec ^. #frontmatter . #optional of rule : _ -> rule ^. #reference; [] -> Nothing)+      assertEqual+        [Just Profile.HumanActor]+        (concatMap (map (^. #format) . (^. #frontmatter . #required)) (spec ^. #types))+      assertEqual [Just "ADR"] (map (^. #idPrefix) (spec ^. #types))++-- | The generation frozen immediately before path-valued reference rules: a+-- descriptor with no @path@ member on 'FieldRule' or 'NestedFieldRule' still+-- loads, every member it did declare survives at both levels and at both nested+-- shapes, and the new member arrives as 'Nothing' everywhere. The fixture writes+-- out every published type it names, unions included, so widening one cannot+-- quietly turn this into a test of the current decoder.+testLoadPrePathCompatibilityFixture :: IO (Either Text ())+testLoadPrePathCompatibilityFixture = do+  path <- fixtureFilePath "profiles/path-references-mp8-ep3.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load frozen pre-path profile: " <> err)+    Right spec -> do+      assertEqual "path-references-mp8-ep3" (spec ^. #name)+      -- The new member is absent everywhere it can appear: three top-level+      -- presence lists, one type scope, and both nested shapes.+      assertEqual [Nothing, Nothing, Nothing] (map (^. #path) (spec ^. #frontmatter . #required))+      assertEqual [Nothing] (map (^. #path) (spec ^. #frontmatter . #recommended))+      assertEqual [Nothing] (map (^. #path) (spec ^. #frontmatter . #optional))+      assertEqual+        [Nothing]+        (concatMap (map (^. #path) . (^. #frontmatter . #required)) (spec ^. #types))+      -- Everything the frozen descriptor did declare survives the upgrade.+      assertEqual+        (Just (handleReferenceRule "ADR" ["mori"] False))+        (case spec ^. #frontmatter . #optional of rule : _ -> rule ^. #reference; [] -> Nothing)+      assertEqual+        [Just Profile.NonNegativeInteger]+        (map (^. #format) (spec ^. #frontmatter . #recommended))+      assertEqual+        [Just Profile.HumanActor]+        (concatMap (map (^. #format) . (^. #frontmatter . #required)) (spec ^. #types))+      case spec ^. #frontmatter . #required of+        [_typeRule, sourcesRule, generatedRule] -> do+          case sourcesRule ^. #elementFields of+            Just NestedRules {presenceConstraints = [], timestampOrderConstraints = [], required = [resourceRule]} -> do+              assertEqual "resource" (resourceRule ^. #field)+              assertEqual Scalar (resourceRule ^. #cardinality)+              assertEqual Nothing (resourceRule ^. #path)+            _ -> Left "expected the frozen element-field rule to survive"+          case generatedRule ^. #objectFields of+            Just NestedRules {presenceConstraints = [], timestampOrderConstraints = [], required = [byRule]} -> do+              assertEqual "by" (byRule ^. #field)+              assertEqual (Just Profile.Actor) (byRule ^. #format)+              assertEqual Nothing (byRule ^. #path)+            _ -> Left "expected the frozen object-member rule to survive"+        _ -> Left "expected three frozen required rules"++-- | The generation frozen immediately before the OKF v0.2 value formats: a+-- descriptor whose records match today's shape but whose @format@ members are+-- typed by the five-alternative format union still loads, and every format it+-- declared arrives as the corresponding current 'FieldFormat'. The fixture+-- writes the union out as a literal rather than importing+-- @okf-core\/dhall\/FieldFormat.dhall@, so widening that file cannot quietly+-- turn this into a test of the current decoder.+testLoadPreActorCompatibilityFixture :: IO (Either Text ())+testLoadPreActorCompatibilityFixture = do+  path <- fixtureFilePath "profiles/formats-mp8-ep2.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load frozen five-alternative format profile: " <> err)+    Right spec -> do+      assertEqual "formats-mp8-ep2" (spec ^. #name)+      assertEqual+        [Nothing, Nothing, Nothing]+        (map (^. #format) (spec ^. #frontmatter . #required))+      assertEqual+        [Just Rfc3339Utc, Just Date]+        (map (^. #format) (spec ^. #frontmatter . #recommended))+      assertEqual+        [Just (UriWithScheme "https"), Just (DocumentHandle "ADR"), Just Uri]+        (map (^. #format) (spec ^. #frontmatter . #optional))+      assertEqual+        [Just Date]+        (concatMap (map (^. #format) . (^. #frontmatter . #required)) (spec ^. #types))+      case spec ^. #frontmatter . #required of+        [_typeRule, _titleRule, generatedRule] ->+          case generatedRule ^. #objectFields of+            Just NestedRules {presenceConstraints = [], timestampOrderConstraints = [], required = [byRule, atRule]} -> do+              assertEqual "by" (byRule ^. #field)+              assertEqual Nothing (byRule ^. #format)+              assertEqual (Just Rfc3339Utc) (atRule ^. #format)+            _ -> Left "expected the frozen object members to survive"+        _ -> Left "expected three frozen required rules"++-- | The generation frozen immediately before object rules: a descriptor that+-- spells out the optional-presence record types with no @objectFields@ member+-- anywhere still loads, keeps every field it did declare — including the+-- @optional@ lists at both scopes and one level of @elementFields@ — and+-- behaves as though every rule declared no object shape.+testLoadPreObjectCompatibilityFixture :: IO (Either Text ())+testLoadPreObjectCompatibilityFixture = do+  path <- fixtureFilePath "profiles/object-fields-mp8-ep1.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load frozen optional-presence profile: " <> err)+    Right spec -> do+      assertEqual "object-fields-mp8-ep1" (spec ^. #name)+      assertEqual+        [Nothing, Nothing]+        (map (^. #objectFields) (spec ^. #frontmatter . #required))+      assertEqual+        [Nothing, Nothing]+        (map (^. #objectFields) (spec ^. #frontmatter . #recommended))+      assertEqual ["supersededBy"] (map (^. #field) (spec ^. #frontmatter . #optional))+      assertEqual [Nothing] (map (^. #objectFields) (spec ^. #frontmatter . #optional))+      case spec ^. #frontmatter . #recommended of+        [referenceRule, reviewsRule] -> do+          assertEqual+            (Just (handleReferenceRule "ADR" ["mori"] False))+            (referenceRule ^. #reference)+          case reviewsRule ^. #elementFields of+            Just NestedRules {presenceConstraints = [], timestampOrderConstraints = [], required = [kindRule], recommended = [notesRule], optional = [urlRule]} -> do+              assertEqual "kind" (kindRule ^. #field)+              assertEqual "notes" (notesRule ^. #field)+              assertEqual "url" (urlRule ^. #field)+            _ -> Left "expected the frozen nested rules to survive with all three presence lists"+        _ -> Left "expected two frozen optional-presence recommended rules"++-- | The backwards-compatibility guarantee: a descriptor frozen in the okf 0.2.x+-- shape — bare-string frontmatter keys, no descriptions anywhere — still loads,+-- via the legacy fallback decoder, with every description absent.+testLoadLegacyProfileFixture :: IO (Either Text ())+testLoadLegacyProfileFixture = do+  path <- fixtureFilePath "profiles/legacy-0.2.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load legacy profile: " <> err)+    Right spec -> do+      assertEqual "legacy" (spec ^. #name)+      assertEqual Nothing (spec ^. #description)+      assertEqual Nothing (spec ^. #guidance)+      assertEqual ["type", "title"] (map (^. #field) (spec ^. #frontmatter . #required))+      assertEqual [Nothing, Nothing] (map (^. #description) (spec ^. #frontmatter . #required))+      assertEqual ["Legacy Concept"] (map (^. #type_) (spec ^. #types))+      assertEqual [Nothing] (map (^. #description) (spec ^. #types))+      assertEqual [Nothing] (map (^. #guidance) (spec ^. #types))+      assertEqual True (spec ^. #allowUnknownFields)+      assertEqual [[], []] (map (^. #allowedValues) (spec ^. #frontmatter . #required))+      assertEqual [Any, Any] (map (^. #cardinality) (spec ^. #frontmatter . #required))++testProfileFieldDescription :: IO (Either Text ())+testProfileFieldDescription = do+  path <- fixtureFilePath "profiles/postgresql.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load profile: " <> err)+    Right spec -> do+      assertEqual+        (Just "Human-readable name of the object, as a reader would say it.")+        (profileFieldDescription spec "title")+      assertEqual+        (Just "postgresql:// URI locating the live object.")+        (profileFieldDescription spec "resource")+      assertEqual Nothing (profileFieldDescription spec "timestamp")+      assertEqual Nothing (profileFieldDescription spec "nope")++-- | Prose declared on an optional rule is as discoverable as prose on a required+-- or recommended one; the third list is searched last, after the two that can+-- produce a missing-field diagnostic.+testOptionalFieldDescription :: IO (Either Text ())+testOptionalFieldDescription = do+  path <- fixtureFilePath "profiles/decisions.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load decisions profile: " <> err)+    Right spec ->+      assertEqual+        (Just "The decision this one replaces, when it replaces one.")+        (profileFieldDescription spec "supersedes")++-- | The JSON encoding is pinned field by field, so a future refactor cannot+-- silently rename a key. The @type@ key matters most: the Haskell field is+-- @type_@, and consumers must never see that.+testProfileJsonShape :: IO (Either Text ())+testProfileJsonShape = do+  path <- fixtureFilePath "profiles/decisions.dhall"+  result <- loadProfileFile path+  pure $ case result of+    Left err -> Left ("failed to load document ID profile: " <> err)+    Right spec ->+      assertEqual+        ( object+            [ "name" .= ("decisions" :: Text),+              "description" .= ("How this team records architectural decisions." :: Text),+              "guidance" .= (Nothing :: Maybe Text),+              "okfVersion" .= ("0.1" :: Text),+              -- Encoded even when absent, so a consumer reads one shape rather+              -- than having to distinguish a missing key from a null one.+              "requireBundleVersion" .= (Nothing :: Maybe Text),+              "allowUnknownTypes" .= False,+              "allowUnknownFields" .= True,+              "idField" .= ("docId" :: Text),+              "frontmatter"+                .= object+                  [ "presenceConstraints" .= ([] :: [PresenceConstraint]),+                    "timestampOrderConstraints" .= ([] :: [TimestampOrderConstraint]),+                    "membershipConstraints" .= ([] :: [MembershipConstraint]),+                    "uniqueValuesConstraints" .= ([] :: [UniqueValuesConstraint]),+                    "required"+                      .= [ object+                             [ "field" .= ("type" :: Text),+                               "description"+                                 .= ("The OKF concept type; must be a type rule below." :: Text),+                               "allowedValues" .= ([] :: [Text]),+                               "cardinality" .= ("any" :: Text),+                               "format" .= (Nothing :: Maybe Text),+                               "elementFields" .= (Nothing :: Maybe Value),+                               "objectFields" .= (Nothing :: Maybe Value),+                               "reference" .= (Nothing :: Maybe HandleReferenceRule),+                               "path" .= (Nothing :: Maybe PathReferenceRule),+                               "when" .= (Nothing :: Maybe FieldCondition),+                               "uniqueBy" .= (Nothing :: Maybe Text)+                             ],+                           object+                             [ "field" .= ("title" :: Text),+                               "description" .= (Nothing :: Maybe Text),+                               "allowedValues" .= ([] :: [Text]),+                               "cardinality" .= ("any" :: Text),+                               "format" .= (Nothing :: Maybe Text),+                               "elementFields" .= (Nothing :: Maybe Value),+                               "objectFields" .= (Nothing :: Maybe Value),+                               "reference" .= (Nothing :: Maybe HandleReferenceRule),+                               "path" .= (Nothing :: Maybe PathReferenceRule),+                               "when" .= (Nothing :: Maybe FieldCondition),+                               "uniqueBy" .= (Nothing :: Maybe Text)+                             ]+                         ],+                    "recommended"+                      .= [ object+                             [ "field" .= ("status" :: Text),+                               "description"+                                 .= ("One of: proposed, accepted, superseded." :: Text),+                               "allowedValues" .= ([] :: [Text]),+                               "cardinality" .= ("any" :: Text),+                               "format" .= (Nothing :: Maybe Text),+                               "elementFields" .= (Nothing :: Maybe Value),+                               "objectFields" .= (Nothing :: Maybe Value),+                               "reference" .= (Nothing :: Maybe HandleReferenceRule),+                               "path" .= (Nothing :: Maybe PathReferenceRule),+                               "when" .= (Nothing :: Maybe FieldCondition),+                               "uniqueBy" .= (Nothing :: Maybe Text)+                             ]+                         ],+                    "optional"+                      .= [ object+                             [ "field" .= ("supersedes" :: Text),+                               "description"+                                 .= ("The decision this one replaces, when it replaces one." :: Text),+                               "allowedValues" .= ([] :: [Text]),+                               "cardinality" .= ("any" :: Text),+                               "format" .= (Nothing :: Maybe Text),+                               "elementFields" .= (Nothing :: Maybe Value),+                               "objectFields" .= (Nothing :: Maybe Value),+                               "reference" .= (Nothing :: Maybe HandleReferenceRule),+                               "path" .= (Nothing :: Maybe PathReferenceRule),+                               "when" .= (Nothing :: Maybe FieldCondition),+                               "uniqueBy" .= (Nothing :: Maybe Text)+                             ]+                         ]+                  ],+              "types"+                .= [ object+                       [ "type" .= ("Decision Record" :: Text),+                         "description"+                           .= ("One accepted decision, never edited after acceptance." :: Text),+                         "guidance" .= (Nothing :: Maybe Text),+                         "frontmatter"+                           .= object+                             [ "presenceConstraints" .= ([] :: [PresenceConstraint]),+                               "timestampOrderConstraints" .= ([] :: [TimestampOrderConstraint]),+                               "membershipConstraints" .= ([] :: [MembershipConstraint]),+                               "uniqueValuesConstraints" .= ([] :: [UniqueValuesConstraint]),+                               "required" .= ([] :: [FieldRule]),+                               "recommended" .= ([] :: [FieldRule]),+                               "optional" .= ([] :: [FieldRule])+                             ],+                         "pathPattern" .= ("decisions/*" :: Text),+                         "resourceScheme" .= (Nothing :: Maybe Text),+                         "requireSchemaSection" .= False,+                         "schemaColumns" .= ([] :: [Text]),+                         "idPrefix" .= ("ADR" :: Text)+                       ]+                   ]+            ]+        )+        (toJSON spec)++testFieldFormatJsonShape :: Either Text ()+testFieldFormatJsonShape =+  assertEqual+    [ String "rfc3339-utc",+      String "date",+      String "uri",+      object ["uriWithScheme" .= ("mori" :: Text)],+      object ["documentHandle" .= ("ADR" :: Text)]+    ]+    (map toJSON [Rfc3339Utc, Date, Uri, UriWithScheme "mori", DocumentHandle "ADR"])++testFieldConditionJsonShape :: Either Text ()+testFieldConditionJsonShape =+  assertEqual+    (object ["field" .= ("status" :: Text), "hasValue" .= (["superseded"] :: [Text])])+    (toJSON (FieldCondition "status" ["superseded"]))++testHandleReferenceJsonShape :: Either Text ()+testHandleReferenceJsonShape =+  assertEqual+    ( object+        [ "localPrefix" .= ("ADR" :: Text),+          "externalUriSchemes" .= (["mori", "https"] :: [Text]),+          "allowSelf" .= False,+          "allowLocal" .= True,+          "externalUriPattern" .= (Nothing :: Maybe Text)+        ]+    )+    (toJSON (handleReferenceRule "ADR" ["mori", "https"] False))++-- | A registry record enumerates every field that decodes as a profile, one+-- level down as well as at the top, sorted by export path. The @Profile@ schema+-- record and the @note@ string contribute nothing.+testRegistryEnumeratesProfiles :: IO (Either Text ())+testRegistryEnumeratesProfiles = do+  path <- fixtureFilePath "registry/package.dhall"+  loaded <- loadRegistry (RegistryFile path)+  pure $ case loaded of+    Left err -> Left ("failed to load fixture registry: " <> err)+    Right entries -> do+      -- `legacy` is a frozen okf 0.2.x descriptor: it enumerates only because+      -- the registry walk falls back to the legacy decoder.+      assertEqual ["legacy", "nested.decisions", "postgresql"] (map (^. #export) entries)+      case findRegistryEntry "legacy" entries of+        Nothing -> Left "expected an entry at export path legacy"+        Just entry -> do+          assertEqual "legacy" (entry ^. #spec . #name)+          assertEqual Nothing (entry ^. #spec . #description)+      case findRegistryEntry "postgresql" entries of+        Nothing -> Left "expected an entry at export path postgresql"+        Just entry -> assertEqual "shinzui-postgresql" (entry ^. #spec . #name)+      assertEqual Nothing (findRegistryEntry "nope" entries)+      assertBool+        "expected findRegistryEntry to resolve the nested export"+        (isJust (findRegistryEntry "nested.decisions" entries))++-- | The built-in registry pin and this offline snapshot move together. Loading+-- the snapshot catches a catalogue descriptor that the current decoder cannot+-- read without making the test suite depend on GitHub or Dhall's cache.+testPinnedCatalogueDecodes :: IO (Either Text ())+testPinnedCatalogueDecodes = do+  path <- fixtureFilePath "catalogue/package.dhall"+  loaded <- loadRegistry (RegistryFile path)+  pure $ case loaded of+    Left err -> Left ("failed to load pinned catalogue snapshot: " <> err)+    Right entries -> do+      assertEqual+        [ "assurance.claimChecks",+          "assurance.failureModes",+          "assurance.reviews",+          "assurance.verificationEvidence",+          "coordination.audiences",+          "coordination.bugReports",+          "coordination.campaigns",+          "coordination.capabilities",+          "coordination.designs",+          "coordination.features",+          "coordination.frictionLog",+          "coordination.improvementRequests",+          "coordination.jobs",+          "coordination.launches",+          "coordination.patternApplications",+          "coordination.strategy",+          "coordination.transitions",+          "coordination.useCases",+          "documentation.architectureDecisions",+          "documentation.messaging",+          "documentation.patternCatalog",+          "documentation.productResearch",+          "documentation.researchDocuments",+          "documentation.runbooks",+          "documentation.specifications",+          "documentation.terminology",+          "documentation.userDocumentation",+          "okfV02",+          "postgresql",+          "tanPostgresql"+        ]+        (List.sort (map (^. #export) entries))+      assertBool+        "expected every pinned catalogue profile to have a non-empty name"+        (all (not . Text.null . (^. #spec . #name)) entries)+      assertBool+        "expected every pinned catalogue profile to have a non-empty okfVersion"+        (all (not . Text.null . (^. #spec . #okfVersion)) entries)++-- | A registry reference that is itself a profile yields one entry whose export+-- path is empty.+testRegistryRootProfile :: IO (Either Text ())+testRegistryRootProfile = do+  path <- fixtureFilePath "profiles/decisions.dhall"+  loaded <- loadRegistry (RegistryFile path)+  pure $ case loaded of+    Left err -> Left ("failed to load root profile registry: " <> err)+    Right entries -> do+      assertEqual [""] (map (^. #export) entries)+      assertEqual ["decisions"] (map (^. #spec . #name) entries)++-- | A directory holding @package.dhall@ resolves to that file; anything else+-- is handed to Dhall verbatim.+testResolveRegistryRef :: IO (Either Text ())+testResolveRegistryRef = do+  directory <- fixturePath "registry"+  resolvedDirectory <- resolveRegistryRef (Text.pack directory)+  filePath <- fixtureFilePath "profiles/decisions.dhall"+  resolvedFile <- resolveRegistryRef (Text.pack filePath)+  resolvedExpression <- resolveRegistryRef "./nowhere/at/all.dhall"+  pure $ do+    assertEqual (RegistryFile (directory </> "package.dhall")) resolvedDirectory+    assertEqual (RegistryFile filePath) resolvedFile+    assertEqual (RegistryExpression "./nowhere/at/all.dhall") resolvedExpression++-- | A reference that cannot be evaluated reports an error rather than throwing.+testRegistryLoadFailure :: IO (Either Text ())+testRegistryLoadFailure = do+  loaded <- loadRegistry (RegistryFile "/nonexistent/registry.dhall")+  pure $ case loaded of+    Right entries -> Left ("expected a load failure, got " <> Text.pack (show (length entries)) <> " entries")+    Left message -> assertBool "expected a non-empty error message" (not (Text.null message))++testLooksLikeRegistryPath :: Either Text ()+testLooksLikeRegistryPath = do+  assertEqual+    [True, True, True, True, True, True, False, False, False]+    ( map+        looksLikeRegistryPath+        [ "./profiles/package.dhall",+          "../profiles/package.dhall",+          "/profiles/package.dhall",+          "~/profiles/package.dhall",+          "profiles/package.dhall",+          "profile.dhall",+          "https://example.test/package.dhall sha256:abc",+          "http://example.test/package.dhall",+          "{ profile = 1 }"+        ]+    )++testRegistryDetailedFailures :: IO (Either Text ())+testRegistryDetailedFailures =+  withDiscoveryTree "okf-registry-errors" [] $ \root -> do+    profilePath <- fixtureFilePath "profiles/decisions.dhall"+    absoluteProfilePath <- makeAbsolute profilePath+    directoryResult <- loadRegistryDetailed (RegistryExpression (Text.pack root))+    missingResult <- loadRegistryDetailed (RegistryExpression (Text.pack (root </> "missing" </> "package.dhall")))+    invalidResult <- loadRegistryDetailed (RegistryExpression "{ profile =")+    hashResult <-+      loadRegistryDetailed+        ( RegistryExpression+            ( Text.pack absoluteProfilePath+                <> " sha256:0000000000000000000000000000000000000000000000000000000000000000"+            )+        )+    pure $ do+      assertEqual (Left (RegistryDirectoryMissingPackage root)) directoryResult+      assertEqual (Left (RegistryPathNotFound (root </> "missing" </> "package.dhall"))) missingResult+      assertEqual (Left RegistryInvalidDhall) invalidResult+      assertEqual (Left RegistryHashMismatch) hashResult+      assertBool+        "typed summaries must not contain ANSI escape bytes"+        ( all+            (not . Text.isInfixOf "\ESC[")+            [ renderRegistryLoadErrorMessage (RegistryDirectoryMissingPackage root),+              renderRegistryLoadErrorMessage RegistryHashMismatch,+              renderRegistryLoadErrorMessage RegistryInvalidDhall+            ]+        )++testDiscoverProfileDescriptors :: IO (Either Text ())+testDiscoverProfileDescriptors = do+  root <- fixturePath "profile-discovery"+  found <-+    ProfileDiscovery.discoverProfileDescriptors+      ProfileDiscovery.defaultProfileDiscoveryOptions+      root+  pure $+    assertEqual+      [ normalise (root </> "nested" </> "valid-nested.dhall"),+        normalise (root </> "valid.dhall")+      ]+      found++testProfileDescriptorQualification :: IO (Either Text ())+testProfileDescriptorQualification = do+  valid <- fixtureFilePath "profile-discovery/valid.dhall"+  registry <- fixtureFilePath "profile-discovery/registry.dhall"+  notProfile <- fixtureFilePath "profile-discovery/not-a-profile.dhall"+  invalid <- fixtureFilePath "profile-discovery/invalid.dhall"+  ignoredFile <- fixtureFilePath "profile-discovery/ignored.txt"+  results <-+    traverse+      ProfileDiscovery.fileQualifiesAsProfileDescriptor+      [valid, registry, notProfile, invalid, ignoredFile]+  pure (assertEqual [True, False, False, False, False] results)++testProfileDiscoveryMissingRoot :: IO (Either Text ())+testProfileDiscoveryMissingRoot = do+  found <-+    ProfileDiscovery.discoverProfileDescriptors+      ProfileDiscovery.defaultProfileDiscoveryOptions+      "/nonexistent/okf-profile-discovery-root"+  pure (assertEqual [] found)++testProfileDiscoverySkipsSymlink :: IO (Either Text ())+testProfileDiscoverySkipsSymlink =+  withDiscoveryTree "okf-profile-discovery-symlink" [] $ \root -> do+    target <- fixtureFilePath "profile-discovery/valid.dhall" >>= makeAbsolute+    createFileLink target (root </> "linked.dhall")+    found <-+      ProfileDiscovery.discoverProfileDescriptors+        ProfileDiscovery.defaultProfileDiscoveryOptions+        root+    pure (assertEqual [] found)++testProfileDiscoveryHonoursMaxDepth :: IO (Either Text ())+testProfileDiscoveryHonoursMaxDepth = do+  root <- fixturePath "profile-discovery"+  shallow <-+    ProfileDiscovery.discoverProfileDescriptors+      ProfileDiscovery.defaultProfileDiscoveryOptions+      root+  deeper <-+    ProfileDiscovery.discoverProfileDescriptors+      ProfileDiscovery.defaultProfileDiscoveryOptions {ProfileDiscovery.maxDepth = 6}+      root+  let deepest = normalise (root </> "deep" </> "a" </> "b" </> "c" </> "d" </> "e" </> "valid-too-deep.dhall")+  pure $ do+    assertBool "default depth should exclude the deep descriptor" (deepest `notElem` shallow)+    assertBool "expanded depth should include the deep descriptor" (deepest `elem` deeper)++testProfileDiscoveryRejectsRemote :: IO (Either Text ())+testProfileDiscoveryRejectsRemote = do+  textRemote <- fixtureFilePath "profile-discovery/remote.dhall"+  bytesRemote <- fixtureFilePath "profile-discovery/remote-bytes.dhall"+  loaded <- traverse ProfileDiscovery.loadProfileDescriptorWithoutNetwork [textRemote, bytesRemote]+  qualifies <- traverse ProfileDiscovery.fileQualifiesAsProfileDescriptor [textRemote, bytesRemote]+  pure $ do+    for_ loaded $ \case+      Right profile -> Left ("expected remote descriptor rejection, decoded " <> profile ^. #name)+      Left message ->+        assertBool+          "expected the dedicated no-network callback to reject the import"+          ("Remote imports are disabled during profile discovery" `Text.isInfixOf` message)+    assertEqual [False, False] qualifies++testProfileSourceLabels :: Either Text ()+testProfileSourceLabels = do+  assertEqual+    "okf-profiles"+    ( renderProfileSourceLabel+        (RegistrySource defaultRegistryReference (RegistryExpression defaultRegistryReference))+    )+  assertEqual+    "okf-v0-2"+    ( renderProfileSourceLabel+        (RegistrySource "docs/profiles/okf-v0-2.dhall" (RegistryFile "docs/profiles/okf-v0-2.dhall"))+    )+  assertEqual "local" (renderProfileSourceLabel (DescriptorSource "docs/profiles/okf-v0-2.dhall"))+  assertEqual+    (Text.pack (normalise "docs/profiles/../profiles/okf-v0-2.dhall"))+    (renderProfileSourceReference (DescriptorSource "docs/profiles/../profiles/okf-v0-2.dhall"))++-- | Loading one source wraps every otherwise unchanged registry entry with its+-- provenance.+testProfileSourceWrapper :: IO (Either Text ())+testProfileSourceWrapper = do+  path <- fixtureFilePath "profiles/decisions.dhall"+  let profileSource = RegistrySource (Text.pack path) (RegistryFile path)+  loaded <- loadProfileSource profileSource+  pure $ case loaded of+    Left err -> Left ("failed to load sourced profile fixture: " <> err)+    Right profiles -> do+      assertEqual [profileSource] (map (^. #source) profiles)+      assertEqual [""] (map (^. #entry . #export) profiles)++testDescriptorSourceWrapper :: IO (Either Text ())+testDescriptorSourceWrapper = do+  path <- fixtureFilePath "profile-discovery/valid.dhall"+  let profileSource = DescriptorSource (normalise path)+  loaded <- loadProfileSource (DescriptorSource (takeDirectory path </> "." </> "valid.dhall"))+  pure $ case loaded of+    Left err -> Left ("failed to load descriptor source fixture: " <> err)+    Right profiles -> do+      assertEqual [profileSource] (map (^. #source) profiles)+      assertEqual ["valid"] (map (^. #entry . #export) profiles)++testDescriptorSourceFailure :: IO (Either Text ())+testDescriptorSourceFailure = do+  path <- fixtureFilePath "profile-discovery/not-a-profile.dhall"+  let profileSource = DescriptorSource path+  (failures, profiles) <- loadProfileSources [profileSource]+  pure $ do+    assertEqual [] profiles+    assertEqual [DescriptorSource (normalise path)] (map (^. #failedSource) failures)+    assertBool+      "expected the descriptor decode failure to carry a reason"+      (all (not . Text.null . (^. #failureReason)) failures)++-- | Multi-source enumeration preserves source order and each registry's+-- export ordering rather than globally interleaving equal-looking paths.+testProfileSourcesMergeInOrder :: IO (Either Text ())+testProfileSourcesMergeInOrder = do+  (publicSource, houseSource) <- fixtureProfileSources+  (failures, profiles) <- loadProfileSources [publicSource, houseSource]+  pure $ do+    assertEqual [] failures+    assertEqual+      [ "legacy",+        "nested.decisions",+        "postgresql",+        "postgresql",+        "runbooks"+      ]+      (map (^. #entry . #export) profiles)+    assertEqual+      (replicate 3 publicSource <> replicate 2 houseSource)+      (map (^. #source) profiles)++testMixedProfileSourcesMergeInOrder :: IO (Either Text ())+testMixedProfileSourcesMergeInOrder = do+  (publicSource, _houseSource) <- fixtureProfileSources+  descriptorPath <- fixtureFilePath "profile-discovery/valid.dhall"+  let descriptorSource = DescriptorSource (normalise descriptorPath)+  (failures, profiles) <- loadProfileSources [publicSource, descriptorSource]+  pure $ do+    assertEqual [] failures+    assertEqual+      ["legacy", "nested.decisions", "postgresql", "valid"]+      (map (^. #entry . #export) profiles)+    assertEqual+      (replicate 3 publicSource <> [descriptorSource])+      (map (^. #source) profiles)++testProfileSourcesPartialFailure :: IO (Either Text ())+testProfileSourcesPartialFailure = do+  (_publicSource, houseSource) <- fixtureProfileSources+  let missingSource = RegistrySource "/nonexistent/registry.dhall" (RegistryFile "/nonexistent/registry.dhall")+  (failures, profiles) <- loadProfileSources [missingSource, houseSource]+  pure $ do+    assertEqual [missingSource] (map (^. #failedSource) failures)+    assertBool+      "expected the captured source failure to include a reason"+      (all (not . Text.null . (^. #failureReason)) failures)+    assertEqual ["postgresql", "runbooks"] (map (^. #entry . #export) profiles)++testProfileSourcesExposeCollisions :: IO (Either Text ())+testProfileSourcesExposeCollisions = do+  (publicSource, houseSource) <- fixtureProfileSources+  (_failures, profiles) <- loadProfileSources [publicSource, houseSource]+  pure $+    assertEqual+      [publicSource, houseSource]+      (map (^. #source) (findSourcedProfiles "postgresql" profiles))++testProfileSourcesDropDuplicates :: IO (Either Text ())+testProfileSourcesDropDuplicates = do+  (_publicSource, houseSource) <- fixtureProfileSources+  (failures, profiles) <- loadProfileSources [houseSource, houseSource]+  pure $ do+    assertEqual [] failures+    assertEqual [houseSource] (normalizeProfileSources [houseSource, houseSource])+    assertEqual ["postgresql", "runbooks"] (map (^. #entry . #export) profiles)++fixtureProfileSources :: IO (ProfileSource, ProfileSource)+fixtureProfileSources = do+  publicPath <- fixtureFilePath "registry/package.dhall"+  housePath <- fixtureFilePath "registry-house/package.dhall"+  pure+    ( RegistrySource (Text.pack publicPath) (RegistryFile publicPath),+      RegistrySource (Text.pack housePath) (RegistryFile housePath)+    )++testParseDocumentId :: Either Text ()+testParseDocumentId = do+  assertEqual+    (Just (DocumentId {prefix = "ADR", number = 7}))+    (parseDocumentId "ADR-7")+  mapM_+    (\invalid -> assertEqual Nothing (parseDocumentId invalid))+    ["ADR-007", "ADR-0", "ADR-", "-7", "ADR 7", "ADR-7-extra"]+  assertEqual (Just "ADR-7") (renderDocumentId <$> parseDocumentId "ADR-7")++testDocumentIdsInBundle :: IO (Either Text ())+testDocumentIdsInBundle = do+  descriptorPath <- fixtureFilePath "profiles/decisions.dhall"+  loaded <- loadProfileFile descriptorPath+  root <- fixturePath "doc-ids"+  concepts <- readBundle root+  pure $ case loaded of+    Left err -> Left ("failed to load document ID profile: " <> err)+    Right spec -> do+      useMarkdown <- parseTestConceptId "decisions/use-markdown"+      usePostgres <- parseTestConceptId "decisions/use-postgres"+      adoptOkf <- parseTestConceptId "decisions/adopt-okf"+      assertEqual+        [ (DocumentId "ADR" 1, useMarkdown),+          (DocumentId "ADR" 2, usePostgres),+          (DocumentId "ADR" 3, adoptOkf)+        ]+        (documentIdsInBundle spec concepts)++testNextDocumentId :: Either Text ()+testNextDocumentId = do+  firstConcept <-+    profileConcept+      "decisions/first"+      [("type", String "Decision Record"), ("title", String "First"), ("docId", String "ADR-1")]+      "# First\n"+  thirdConcept <-+    profileConcept+      "decisions/third"+      [("type", String "Decision Record"), ("title", String "Third"), ("docId", String "ADR-3")]+      "# Third\n"+  let concepts = [firstConcept, thirdConcept]+  assertEqual (DocumentId "ADR" 4) (nextDocumentId testDocumentIdProfileSpec concepts "ADR")+  assertEqual (DocumentId "RFC" 1) (nextDocumentId testDocumentIdProfileSpec concepts "RFC")++testFindConceptsByDocumentId :: IO (Either Text ())+testFindConceptsByDocumentId = do+  validRoot <- fixturePath "doc-ids"+  validConcepts <- readBundle validRoot+  deviationRoot <- fixturePath "doc-id-deviations"+  deviationConcepts <- readBundle deviationRoot+  pure $ do+    usePostgres <- parseTestConceptId "decisions/use-postgres"+    firstId <- parseTestConceptId "decisions/first"+    secondId <- parseTestConceptId "decisions/second"+    assertEqual+      [usePostgres]+      (conceptIdOf <$> findConceptsByDocumentId Nothing "ADR-2" validConcepts)+    assertEqual+      [firstId, secondId]+      (conceptIdOf <$> findConceptsByDocumentId (Just "docId") "ADR-1" deviationConcepts)++-- | An undocumented frontmatter key: the validation tests care about names, not+-- prose, and descriptions never affect validation.+requiredField :: Text -> FieldRule+requiredField key = FieldRule {field = key, description = Nothing, allowedValues = [], cardinality = Any, format = Nothing, elementFields = Nothing, objectFields = Nothing, reference = Nothing, path = Nothing, when = Nothing, uniqueBy = Nothing}++-- | Build a 'FieldRule' positionally in the argument order this file used+-- before 'FieldRule' gained @objectFields@, filling that member in as+-- 'Nothing'. The dozens of call sites below constrain lists, formats,+-- conditions, and references rather than object shapes, so spelling out a ninth+-- 'Nothing' at each of them would add noise and no information. A test that+-- does exercise object rules builds its rule with record syntax instead.+fieldRule ::+  Text ->+  Maybe Text ->+  [Text] ->+  Cardinality ->+  Maybe FieldFormat ->+  Maybe NestedRules ->+  Maybe HandleReferenceRule ->+  Maybe FieldCondition ->+  FieldRule+fieldRule key description allowedValues cardinality format elementFields reference condition =+  FieldRule+    { field = key,+      description,+      allowedValues,+      cardinality,+      format,+      elementFields,+      objectFields = Nothing,+      reference,+      path = Nothing,+      when = condition,+      uniqueBy = Nothing+    }++handleReferenceRule :: Text -> [Text] -> Bool -> HandleReferenceRule+handleReferenceRule prefix schemes selfAllowed =+  HandleReferenceRule+    { localPrefix = prefix,+      externalUriSchemes = schemes,+      allowSelf = selfAllowed,+      allowLocal = True,+      externalUriPattern = Nothing+    }++nestedFieldRule :: Text -> Maybe Text -> [Text] -> Cardinality -> Maybe FieldFormat -> Maybe PathReferenceRule -> Maybe FieldCondition -> NestedFieldRule+nestedFieldRule key description allowedValues cardinality format path condition =+  NestedFieldRule+    { field = key,+      description,+      allowedValues,+      cardinality,+      format,+      path,+      when = condition,+      reference = Nothing+    }++-- | A standalone profile literal so the validation tests do not depend on the+-- Dhall fixture. One rule: PostgreSQL Table, fully constrained.+testProfileSpec :: ProfileSpec+testProfileSpec =+  ProfileSpec+    { name = "test-postgresql",+      description = Nothing,+      guidance = Nothing,+      okfVersion = "0.1",+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [requiredField "type", requiredField "title"],+            recommended = [],+            optional = []+          },+      allowUnknownTypes = False,+      allowUnknownFields = True,+      idField = Nothing,+      requireBundleVersion = Nothing,+      types =+        [ TypeRule+            { type_ = "PostgreSQL Table",+              description = Nothing,+              guidance = Nothing,+              frontmatter = emptyTestFrontmatterRules,+              pathPattern = Just "schemas/*/tables/*",+              resourceScheme = Just "postgresql",+              requireSchemaSection = True,+              schemaColumns = ["Column", "Type", "Nullable", "Description"],+              idPrefix = Nothing+            }+        ]+    }++testDocumentIdProfileSpec :: ProfileSpec+testDocumentIdProfileSpec =+  ProfileSpec+    { name = "test-decisions",+      description = Nothing,+      guidance = Nothing,+      okfVersion = "0.1",+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [requiredField "type", requiredField "title"],+            recommended = [],+            optional = []+          },+      allowUnknownTypes = False,+      allowUnknownFields = True,+      idField = Just "docId",+      requireBundleVersion = Nothing,+      types =+        [ TypeRule+            { type_ = "Decision Record",+              description = Nothing,+              guidance = Nothing,+              frontmatter = emptyTestFrontmatterRules,+              pathPattern = Just "decisions/*",+              resourceScheme = Nothing,+              requireSchemaSection = False,+              schemaColumns = [],+              idPrefix = Just "ADR"+            }+        ]+    }++emptyTestFrontmatterRules :: FrontmatterRules+emptyTestFrontmatterRules = FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [], recommended = [], optional = []}++typeAwareProfileSpec :: ProfileSpec+typeAwareProfileSpec =+  ProfileSpec+    { name = "type-aware",+      description = Nothing,+      guidance = Nothing,+      okfVersion = "0.1",+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing, fieldRule "title" (Just "Global title.") [] Any Nothing Nothing Nothing Nothing],+            recommended = [fieldRule "owner" (Just "Profile-level owner.") [] Any Nothing Nothing Nothing Nothing],+            optional = []+          },+      allowUnknownTypes = True,+      allowUnknownFields = True,+      idField = Nothing,+      requireBundleVersion = Nothing,+      types =+        [ TypeRule+            { type_ = "Owned Concept",+              description = Nothing,+              guidance = Nothing,+              frontmatter =+                FrontmatterRules+                  { membershipConstraints = [],+                    uniqueValuesConstraints = [],+                    presenceConstraints = [],+                    timestampOrderConstraints = [],+                    required = [fieldRule "owner" (Just "Responsible person.") [] Any Nothing Nothing Nothing Nothing],+                    recommended = [fieldRule "reviewer" (Just "Second pair of eyes.") [] Any Nothing Nothing Nothing Nothing, fieldRule "title" (Just "Type title.") [] Any Nothing Nothing Nothing Nothing],+                    optional = []+                  },+              pathPattern = Nothing,+              resourceScheme = Nothing,+              requireSchemaSection = False,+              schemaColumns = [],+              idPrefix = Nothing+            }+        ]+    }++testCompileProfileDefinitionErrors :: Either Text ()+testCompileProfileDefinitionErrors = do+  let duplicateField = fieldRule "title" Nothing [] Any Nothing Nothing Nothing Nothing+      invalid =+        typeAwareProfileSpec+          { frontmatter =+              FrontmatterRules+                { membershipConstraints = [],+                  uniqueValuesConstraints = [],+                  presenceConstraints = [],+                  timestampOrderConstraints = [],+                  required = [duplicateField, duplicateField],+                  recommended = [duplicateField],+                  optional = []+                },+            types = (typeAwareProfileSpec ^. #types) <> (typeAwareProfileSpec ^. #types)+          }+  case compileProfile invalid of+    Right _ -> Left "expected invalid profile definition"+    Left errors ->+      assertEqual+        [ DuplicateFieldRule Nothing "required" "title",+          ConflictingFieldRequirement Nothing "title",+          DuplicateTypeRule "Owned Concept"+        ]+        (toList errors)++testCompiledProfileMerge :: Either Text ()+testCompiledProfileMerge = do+  compiled <- firstShow (compileProfile typeAwareProfileSpec)+  assertEqual (Just "Type title.") (profileFieldDescriptionForType compiled "Owned Concept" "title")+  assertEqual (Just "Responsible person.") (profileFieldDescriptionForType compiled "Owned Concept" "owner")+  assertEqual (Just "Global title.") (profileFieldDescriptionForType compiled "Unknown Concept" "title")+  concept <- profileConcept "owned/one" [("type", String "Owned Concept")] "# One\n"+  cid <- parseTestConceptId "owned/one"+  assertEqual+    [MissingProfileField cid "owner" Nothing, MissingProfileField cid "title" Nothing]+    (validateProfile PermissiveConformance compiled [concept])++vocabularyProfileSpec :: ProfileSpec+vocabularyProfileSpec =+  typeAwareProfileSpec+    { frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing],+            recommended = [fieldRule "status" Nothing ["draft", "approved", "approved"] Any Nothing Nothing Nothing Nothing],+            optional = []+          },+      types =+        [ withTypeFrontmatter+            FrontmatterRules+              { membershipConstraints = [],+                uniqueValuesConstraints = [],+                presenceConstraints = [],+                timestampOrderConstraints = [],+                required = [fieldRule "status" Nothing ["approved", "archived"] Any Nothing Nothing Nothing Nothing],+                recommended = [],+                optional = []+              }+            (firstTypeRule typeAwareProfileSpec)+        ]+    }++fieldPath :: Text -> FieldPath+fieldPath key = FieldPath (FieldName key :| [])++testCompiledVocabularyIntersection :: Either Text ()+testCompiledVocabularyIntersection = do+  compiled <- firstShow (compileProfile vocabularyProfileSpec)+  concept <- profileConcept "owned/one" [("type", String "Owned Concept"), ("status", String "draft")] "# One\n"+  cid <- parseTestConceptId "owned/one"+  assertEqual+    [ValueNotInVocabulary cid (fieldPath "status") ["approved"] (String "draft")]+    (validateProfile PermissiveConformance compiled [concept])++testUnsatisfiableVocabulary :: Either Text ()+testUnsatisfiableVocabulary = do+  let disjoint =+        vocabularyProfileSpec+          { types =+              [ withTypeFrontmatter+                  FrontmatterRules+                    { membershipConstraints = [],+                      uniqueValuesConstraints = [],+                      presenceConstraints = [],+                      timestampOrderConstraints = [],+                      required = [fieldRule "status" Nothing ["closed"] Any Nothing Nothing Nothing Nothing],+                      recommended = [],+                      optional = []+                    }+                  (firstTypeRule vocabularyProfileSpec)+              ]+          }+  assertEqual+    (Left (UnsatisfiableVocabulary (Just "Owned Concept") "status" ["draft", "approved"] ["closed"] :| []))+    (compileProfile disjoint)++testCompiledCardinality :: Either Text ()+testCompiledCardinality = do+  let profileRules =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing],+            recommended = [fieldRule "status" Nothing [] Scalar Nothing Nothing Nothing Nothing],+            optional = []+          }+      typeRules cardinality =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [fieldRule "status" Nothing [] cardinality Nothing Nothing Nothing Nothing],+            recommended = [],+            optional = []+          }+      baseType = firstTypeRule typeAwareProfileSpec+      compatible =+        typeAwareProfileSpec+          { frontmatter = profileRules,+            types = [withTypeFrontmatter (typeRules Any) baseType]+          }+      contradictory = compatible {types = [withTypeFrontmatter (typeRules List) baseType]}+  compiled <- firstShow (compileProfile compatible)+  valid <- profileConcept "owned/cardinality" [("type", String "Owned Concept"), ("status", Number 3)] "# Valid\n"+  invalid <- profileConcept "owned/cardinality" [("type", String "Owned Concept"), ("status", toJSON (["draft"] :: [Text]))] "# Invalid\n"+  cid <- parseTestConceptId "owned/cardinality"+  assertEqual [] (validateProfile PermissiveConformance compiled [valid])+  assertEqual+    [CardinalityMismatch cid (fieldPath "status") Scalar (toJSON (["draft"] :: [Text]))]+    (validateProfile PermissiveConformance compiled [invalid])+  assertEqual+    (Left (ConflictingCardinality (Just "Owned Concept") "status" Scalar List :| []))+    (compileProfile contradictory)++testVocabularyValidation :: Either Text ()+testVocabularyValidation = do+  let openVocabulary =+        vocabularyProfileSpec+          { frontmatter =+              FrontmatterRules+                { membershipConstraints = [],+                  uniqueValuesConstraints = [],+                  presenceConstraints = [],+                  timestampOrderConstraints = [],+                  required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing],+                  recommended = [fieldRule "status" Nothing ["draft", "approved"] Any Nothing Nothing Nothing Nothing],+                  optional = []+                },+            types = []+          }+  compiled <- firstShow (compileProfile openVocabulary)+  validString <- profileConcept "valid-string" [("type", String "Extension"), ("status", String "draft")] "# Valid\n"+  validList <- profileConcept "valid-list" [("type", String "Extension"), ("status", toJSON (["draft", "approved"] :: [Text]))] "# Valid\n"+  absent <- profileConcept "absent" [("type", String "Extension")] "# Absent\n"+  invalidString <- profileConcept "invalid-string" [("type", String "Extension"), ("status", String "banana")] "# Invalid\n"+  invalidList <- profileConcept "invalid-list" [("type", String "Extension"), ("status", toJSON (["draft", "banana"] :: [Text]))] "# Invalid\n"+  invalidShape <- profileConcept "invalid-shape" [("type", String "Extension"), ("status", toJSON (1 :: Int))] "# Invalid\n"+  invalidStringId <- parseTestConceptId "invalid-string"+  invalidListId <- parseTestConceptId "invalid-list"+  invalidShapeId <- parseTestConceptId "invalid-shape"+  assertEqual [] (validateProfile PermissiveConformance compiled [validString, validList, absent])+  assertEqual+    [ValueNotInVocabulary invalidStringId (fieldPath "status") ["draft", "approved"] (String "banana")]+    (validateProfile PermissiveConformance compiled [invalidString])+  assertEqual+    [ValueNotInVocabulary invalidListId (fieldPath "status") ["draft", "approved"] (toJSON (["draft", "banana"] :: [Text]))]+    (validateProfile PermissiveConformance compiled [invalidList])+  assertEqual+    [ValueNotInVocabulary invalidShapeId (fieldPath "status") ["draft", "approved"] (toJSON (1 :: Int))]+    (validateProfile PermissiveConformance compiled [invalidShape])++testCardinalityValidation :: Either Text ()+testCardinalityValidation = do+  cid <- parseTestConceptId "cardinality"+  let check cardinality actual = do+        compiled <- firstShow (compileProfile (singleCardinalityProfile True cardinality []))+        concept <- profileConcept "cardinality" [("type", String "Extension"), ("value", actual)] "# Cardinality\n"+        pure (validateProfile PermissiveConformance compiled [concept])+      mismatch cardinality actual = [CardinalityMismatch cid (fieldPath "value") cardinality actual]+      objectValue = object ["nested" .= (True :: Bool)]+      textList = toJSON (["one"] :: [Text])+      emptyList = toJSON ([] :: [Text])+  for_ [String "one", Number 0, Bool False] $ \actual ->+    check Scalar actual >>= assertEqual []+  for_ [textList, objectValue, Null] $ \actual ->+    check Scalar actual >>= assertEqual (mismatch Scalar actual)+  check List textList >>= assertEqual []+  for_ [String "one", Number 0, Bool False, objectValue, Null] $ \actual ->+    check List actual >>= assertEqual (mismatch List actual)+  check Any (String "one") >>= assertEqual []+  check Any textList >>= assertEqual []+  check Any (Bool False) >>= assertEqual [MissingProfileField cid "value" Nothing]+  check Scalar (String "   ") >>= assertEqual [MissingProfileField cid "value" Nothing]+  check List emptyList >>= assertEqual [MissingProfileField cid "value" Nothing]+  optionalCompiled <- firstShow (compileProfile (singleCardinalityProfile False Scalar []))+  optionalConcept <- profileConcept "cardinality" [("type", String "Extension"), ("value", textList)] "# Optional\n"+  assertEqual+    (mismatch Scalar textList)+    (validateProfile PermissiveConformance optionalCompiled [optionalConcept])++testCardinalityVocabularyInteraction :: Either Text ()+testCardinalityVocabularyInteraction = do+  cid <- parseTestConceptId "cardinality"+  scalarCompiled <- firstShow (compileProfile (singleCardinalityProfile True Scalar ["draft"]))+  let objectValue = object ["status" .= ("draft" :: Text)]+  objectConcept <- profileConcept "cardinality" [("type", String "Extension"), ("value", objectValue)] "# Object\n"+  assertEqual+    [CardinalityMismatch cid (fieldPath "value") Scalar objectValue]+    (validateProfile PermissiveConformance scalarCompiled [objectConcept])+  listCompiled <- firstShow (compileProfile (singleCardinalityProfile True List ["draft"]))+  let mixedList = toJSON ([String "draft", Number 1] :: [Value])+  listConcept <- profileConcept "cardinality" [("type", String "Extension"), ("value", mixedList)] "# List\n"+  assertEqual+    [ValueNotInVocabulary cid (fieldPath "value") ["draft"] mixedList]+    (validateProfile PermissiveConformance listCompiled [listConcept])++testCompiledFieldFormats :: Either Text ()+testCompiledFieldFormats = do+  let baseType = firstTypeRule typeAwareProfileSpec+      profileWith profileFormat typeFormat =+        typeAwareProfileSpec+          { frontmatter =+              FrontmatterRules+                { membershipConstraints = [],+                  uniqueValuesConstraints = [],+                  presenceConstraints = [],+                  timestampOrderConstraints = [],+                  required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing, fieldRule "homepage" Nothing [] Any (Just profileFormat) Nothing Nothing Nothing],+                  recommended = [],+                  optional = []+                },+            types =+              [ withTypeFrontmatter+                  FrontmatterRules+                    { membershipConstraints = [],+                      uniqueValuesConstraints = [],+                      presenceConstraints = [],+                      timestampOrderConstraints = [],+                      required = [fieldRule "homepage" Nothing [] Any (Just typeFormat) Nothing Nothing Nothing],+                      recommended = [],+                      optional = []+                    }+                  baseType+              ]+          }+  refined <- firstShow (compileProfile (profileWith Uri (UriWithScheme "https")))+  valid <- profileConcept "format-refinement" [("type", String "Owned Concept"), ("homepage", String "HTTPS://example.test/path")] "# Valid\n"+  invalid <- profileConcept "format-refinement" [("type", String "Owned Concept"), ("homepage", String "http://example.test/path")] "# Invalid\n"+  cid <- parseTestConceptId "format-refinement"+  assertEqual [] (validateProfile PermissiveConformance refined [valid])+  assertEqual+    [ValueFormatMismatch cid (fieldPath "homepage") (UriWithScheme "https") (String "http://example.test/path")]+    (validateProfile PermissiveConformance refined [invalid])+  assertEqual+    (Left (ConflictingFieldFormat (fieldPath "homepage") Date Rfc3339Utc :| []))+    (compileProfile (profileWith Date Rfc3339Utc))++testInvalidFormatParameters :: Either Text ()+testInvalidFormatParameters = do+  let invalid =+        typeAwareProfileSpec+          { frontmatter =+              FrontmatterRules+                { membershipConstraints = [],+                  uniqueValuesConstraints = [],+                  presenceConstraints = [],+                  timestampOrderConstraints = [],+                  required =+                    [ fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing,+                      fieldRule "handle" Nothing [] Any (Just (DocumentHandle "1ADR")) Nothing Nothing Nothing,+                      fieldRule "source" Nothing [] Any (Just (UriWithScheme "https_")) Nothing Nothing Nothing+                    ],+                  recommended = [],+                  optional = []+                },+            types = []+          }+  assertEqual+    ( Left+        ( InvalidFormatParameter (fieldPath "handle") (DocumentHandle "1ADR") "1ADR"+            :| [InvalidFormatParameter (fieldPath "source") (UriWithScheme "https_") "https_"]+        )+    )+    (compileProfile invalid)++testNamedFormatValidation :: Either Text ()+testNamedFormatValidation = do+  cid <- parseTestConceptId "format"+  let check fieldFormat cardinality actual = do+        compiled <- firstShow (compileProfile (singleFormatProfile cardinality fieldFormat))+        concept <-+          profileConcept+            "format"+            ([("type", String "Extension")] <> maybe [] (\value -> [("value", value)]) actual)+            "# Format\n"+        pure (validateProfile PermissiveConformance compiled [concept])+      mismatch fieldFormat actual = [ValueFormatMismatch cid (fieldPath "value") fieldFormat actual]+  for_ ["2024-02-29T23:59:59Z", "2026-07-29T17:00:00.125Z"] $ \value ->+    check Rfc3339Utc Any (Just (String value)) >>= assertEqual []+  for_ ["2026-13-45T99:99:99Z", "2026-07-29T17:00:00+01:00", "2026-07-29 17:00:00Z"] $ \value ->+    check Rfc3339Utc Any (Just (String value)) >>= assertEqual (mismatch Rfc3339Utc (String value))+  check Date Any (Just (String "2024-02-29")) >>= assertEqual []+  for_ ["2023-02-29", "2026-13-01", "2026-07-29T00:00:00Z"] $ \value ->+    check Date Any (Just (String value)) >>= assertEqual (mismatch Date (String value))+  for_ ["https://example.test/path", "urn:example:item"] $ \value ->+    check Uri Any (Just (String value)) >>= assertEqual []+  for_ ["relative/path", "https://example.test/bad%ZZ"] $ \value ->+    check Uri Any (Just (String value)) >>= assertEqual (mismatch Uri (String value))+  check (UriWithScheme "mori") Any (Just (String "MORI://haskell/time")) >>= assertEqual []+  check (UriWithScheme "mori") Any (Just (String "https://example.test"))+    >>= assertEqual (mismatch (UriWithScheme "mori") (String "https://example.test"))+  check (DocumentHandle "ADR") Any (Just (String "ADR-7")) >>= assertEqual []+  for_ ["ADR-007", "IR-7"] $ \value ->+    check (DocumentHandle "ADR") Any (Just (String value))+      >>= assertEqual (mismatch (DocumentHandle "ADR") (String value))+  let validUris = toJSON (["https://example.test", "urn:example:item"] :: [Text])+      mixedUris = toJSON ([String "https://example.test", Number 1] :: [Value])+  check Uri List (Just validUris) >>= assertEqual []+  check Uri List (Just mixedUris) >>= assertEqual (mismatch Uri mixedUris)+  check Uri Scalar (Just validUris)+    >>= assertEqual [CardinalityMismatch cid (fieldPath "value") Scalar validUris]+  check Uri Any (Just (Number 1)) >>= assertEqual (mismatch Uri (Number 1))+  check Uri Any Nothing >>= assertEqual []++-- | The OKF v0.2 actor formats. Specification §7 defines exactly three shapes+-- and 'parseActor' classifies them, so @actor@ accepts those three and reports+-- everything else — including the specification's own illustrative+-- @author: team:ga4-docs@ from §5.1, which §7's convention does not define. The+-- case-sensitivity and empty-component cases come from 'Okf.Actor'.+testActorFormatValidation :: Either Text ()+testActorFormatValidation = do+  cid <- parseTestConceptId "format"+  let check fieldFormat value = do+        compiled <- firstShow (compileProfile (singleFormatProfile Any fieldFormat))+        concept <-+          profileConcept "format" [("type", String "Extension"), ("value", String value)] "# Format\n"+        pure (validateProfile PermissiveConformance compiled [concept])+      mismatch fieldFormat value = [ValueFormatMismatch cid (fieldPath "value") fieldFormat (String value)]+  for_ ["human:ahormati", "process:finance-nightly", "reference_agent/gemini-2.5-pro"] $ \value ->+    check Actor value >>= assertEqual []+  for_ ["nadeem", "team:ga4-docs", "Human:ahormati", "human:", "/version", "producer/"] $ \value ->+    check Actor value >>= assertEqual (mismatch Actor value)+  check Profile.HumanActor "human:ahormati" >>= assertEqual []+  for_ ["process:finance-nightly", "reference_agent/gemini-2.5-pro", "nadeem"] $ \value ->+    check Profile.HumanActor value >>= assertEqual (mismatch Profile.HumanActor value)++-- | The non-textual formats. A numeric /string/ is reported rather than+-- coerced, which is the point of being able to declare the format at all.+testNonTextualFormatValidation :: Either Text ()+testNonTextualFormatValidation = do+  cid <- parseTestConceptId "format"+  let checkWith cardinality fieldFormat actual = do+        compiled <- firstShow (compileProfile (singleFormatProfile cardinality fieldFormat))+        concept <-+          profileConcept "format" [("type", String "Extension"), ("value", actual)] "# Format\n"+        pure (validateProfile PermissiveConformance compiled [concept])+      check = checkWith Any+      mismatch fieldFormat actual = [ValueFormatMismatch cid (fieldPath "value") fieldFormat actual]+  for_ [Number 5000, Number 0, Number (-3)] $ \actual ->+    check Integer actual >>= assertEqual []+  for_ [Number 5000, Number 0] $ \actual ->+    check NonNegativeInteger actual >>= assertEqual []+  check NonNegativeInteger (Number (-3)) >>= assertEqual (mismatch NonNegativeInteger (Number (-3)))+  for_ [Integer, NonNegativeInteger] $ \fieldFormat ->+    for_ [String "5000", Number 5.5, Bool True] $ \actual ->+      check fieldFormat actual >>= assertEqual (mismatch fieldFormat actual)+  for_ [Bool True, Bool False] $ \actual ->+    check Boolean actual >>= assertEqual []+  for_ [String "true", Number 1] $ \actual ->+    check Boolean actual >>= assertEqual (mismatch Boolean actual)+  -- A list is a list of values, so a format constrains each element. The+  -- cardinality has to be declared, because a numeric format alone refines an+  -- unspecified one to scalar.+  let integers = toJSON ([1, 2, 3] :: [Int])+      mixed = toJSON ([Number 1, String "2"] :: [Value])+  checkWith List Integer integers >>= assertEqual []+  checkWith List Integer mixed >>= assertEqual (mismatch Integer mixed)++-- | Declaring a non-textual format and no cardinality refines the rule to+-- 'Scalar'. Without the refinement the 'Any' cardinality routes presence through+-- the legacy predicate, which counts only non-empty text and non-empty arrays,+-- so a present @usage_count: 5000@ is reported /missing/ before its value is+-- ever examined. An explicitly declared cardinality still wins.+testNonTextualFormatRefinesCardinality :: Either Text ()+testNonTextualFormatRefinesCardinality = do+  cid <- parseTestConceptId "counted"+  let specWith cardinality fieldFormat =+        typeAwareProfileSpec+          { frontmatter =+              FrontmatterRules+                { membershipConstraints = [],+                  uniqueValuesConstraints = [],+                  presenceConstraints = [],+                  timestampOrderConstraints = [],+                  required =+                    [ fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing,+                      fieldRule "usage_count" Nothing [] cardinality (Just fieldFormat) Nothing Nothing Nothing+                    ],+                  recommended = [],+                  optional = []+                },+            allowUnknownTypes = True,+            types = []+          }+      check cardinality fieldFormat actual = do+        compiled <- firstShow (compileProfile (specWith cardinality fieldFormat))+        concept <-+          profileConcept "counted" [("type", String "Extension"), ("usage_count", actual)] "# Counted\n"+        pure (validateProfile PermissiveConformance compiled [concept])+  for_ [NonNegativeInteger, Integer] $ \fieldFormat ->+    check Any fieldFormat (Number 5000) >>= assertEqual []+  check Any Boolean (Bool False) >>= assertEqual []+  -- The gap this closes: a textual format leaves the rule at 'Any', where a+  -- number still does not count as present. The value check runs regardless of+  -- the presence verdict, so both violations are reported.+  check Any Rfc3339Utc (Number 5000)+    >>= assertEqual+      [ MissingProfileField cid "usage_count" Nothing,+        ValueFormatMismatch cid (fieldPath "usage_count") Rfc3339Utc (Number 5000)+      ]+  -- An explicit cardinality wins, and a list of integers stays coherent rather+  -- than becoming an error.+  let integers = toJSON ([1, 2] :: [Int])+  check List NonNegativeInteger integers >>= assertEqual []+  check Scalar NonNegativeInteger integers+    >>= assertEqual [CardinalityMismatch cid (fieldPath "usage_count") Scalar integers]++-- | The two new narrowing pairs, checked the way the 'Uri'/'UriWithScheme' pair+-- is: a profile-scope format and a narrower type-scope one compile to the+-- narrower rule rather than to a 'ConflictingFieldFormat'.+testNewFormatsNarrowAcrossScopes :: Either Text ()+testNewFormatsNarrowAcrossScopes = do+  cid <- parseTestConceptId "narrowing"+  let baseType = firstTypeRule typeAwareProfileSpec+      profileWith profileFormat typeFormat =+        typeAwareProfileSpec+          { -- v0.2, for the same reason 'singleFormatProfile' is: the narrowing+            -- pairs under test include the actor formats.+            okfVersion = "0.2",+            frontmatter =+              FrontmatterRules+                { membershipConstraints = [],+                  uniqueValuesConstraints = [],+                  presenceConstraints = [],+                  timestampOrderConstraints = [],+                  required =+                    [ fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing,+                      fieldRule "value" Nothing [] Any (Just profileFormat) Nothing Nothing Nothing+                    ],+                  recommended = [],+                  optional = []+                },+            types =+              [ withTypeFrontmatter+                  FrontmatterRules+                    { membershipConstraints = [],+                      uniqueValuesConstraints = [],+                      presenceConstraints = [],+                      timestampOrderConstraints = [],+                      required = [fieldRule "value" Nothing [] Any (Just typeFormat) Nothing Nothing Nothing],+                      recommended = [],+                      optional = []+                    }+                  baseType+              ]+          }+      check profileFormat typeFormat actual = do+        compiled <- firstShow (compileProfile (profileWith profileFormat typeFormat))+        concept <-+          profileConcept "narrowing" [("type", String "Owned Concept"), ("value", actual)] "# Narrowing\n"+        pure (validateProfile PermissiveConformance compiled [concept])+  for_ [(Actor, Profile.HumanActor), (Profile.HumanActor, Actor)] $ \(wide, narrow) -> do+    check wide narrow (String "human:ahormati") >>= assertEqual []+    check wide narrow (String "process:nightly")+      >>= assertEqual+        [ValueFormatMismatch cid (fieldPath "value") Profile.HumanActor (String "process:nightly")]+  for_ [(Integer, NonNegativeInteger), (NonNegativeInteger, Integer)] $ \(wide, narrow) -> do+    check wide narrow (Number 5000) >>= assertEqual []+    check wide narrow (Number (-3))+      >>= assertEqual+        [ValueFormatMismatch cid (fieldPath "value") NonNegativeInteger (Number (-3))]+  assertEqual+    (Left (ConflictingFieldFormat (fieldPath "value") Actor Integer :| []))+    (compileProfile (profileWith Actor Integer))++-- | Declares @okfVersion = "0.2"@ rather than inheriting 'typeAwareProfileSpec'\'s+-- @"0.1"@, because the formats under test include the OKF v0.2 actor+-- convention, and 'compileProfile' rejects a v0.2 format under a v0.1+-- declaration.+singleFormatProfile :: Cardinality -> FieldFormat -> ProfileSpec+singleFormatProfile cardinality fieldFormat =+  typeAwareProfileSpec+    { okfVersion = "0.2",+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing],+            recommended = [fieldRule "value" Nothing [] cardinality (Just fieldFormat) Nothing Nothing Nothing],+            optional = []+          },+      allowUnknownTypes = True,+      types = []+    }++singleCardinalityProfile :: Bool -> Cardinality -> [Text] -> ProfileSpec+singleCardinalityProfile isRequired cardinality allowed =+  typeAwareProfileSpec+    { frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing] <> [rule | isRequired],+            recommended = [rule | not isRequired],+            optional = []+          },+      allowUnknownTypes = True,+      types = []+    }+  where+    rule = fieldRule "value" Nothing allowed cardinality Nothing Nothing Nothing Nothing++testCompiledNestedRules :: Either Text ()+testCompiledNestedRules = do+  let profileRules =+        NestedRules+          { allowUnknownFields = True,+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [nestedFieldRule "kind" Nothing ["decision", "implementation"] Any Nothing Nothing Nothing],+            recommended = [nestedFieldRule "notes" Nothing [] Scalar Nothing Nothing Nothing],+            optional = []+          }+      typeRules =+        NestedRules+          { allowUnknownFields = True,+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required =+              [ nestedFieldRule "kind" Nothing ["implementation", "operations"] Any Nothing Nothing Nothing,+                nestedFieldRule "outcome" Nothing ["approved", "rejected"] Any Nothing Nothing Nothing+              ],+            recommended = [],+            optional = []+          }+      base = nestedProfileWithRules Any profileRules (Just typeRules)+  compiled <- firstShow (compileProfile base)+  concept <-+    profileConcept+      "reviewed/merge"+      [ ("type", String "Reviewed Concept"),+        ( "reviews",+          toJSON+            [ object+                [ "kind" .= ("decision" :: Text),+                  "outcome" .= ("approved" :: Text)+                ]+            ]+        )+      ]+      "# Merge\n"+  cid <- parseTestConceptId "reviewed/merge"+  assertEqual+    [ ValueNotInVocabulary+        cid+        (nestedTestPath 0 "kind")+        ["implementation"]+        (String "decision")+    ]+    (validateProfile PermissiveConformance compiled [concept])+  let impossible = nestedProfileWithRules Scalar profileRules Nothing+  assertEqual+    (Left (ElementFieldsRequireList Nothing (fieldPath "reviews") Scalar :| []))+    (compileProfile impossible)++testNestedRecordValidation :: Either Text ()+testNestedRecordValidation = do+  compiled <- firstShow (compileProfile nestedReviewProfileSpec)+  let firstReview =+        object+          [ "kind" .= ("human" :: Text),+            "reviewer" .= ("Ari" :: Text),+            "reviewed_at" .= ("2026-07-29T16:00:00Z" :: Text),+            "document_timestamp" .= ("2026-07-29T17:00:00Z" :: Text),+            "scope" .= ("content" :: Text),+            "outcome" .= ("approved" :: Text),+            "context" .= ("Complete" :: Text),+            "notes" .= ("No blockers" :: Text),+            "provider" .= ("allowed-extra-key" :: Text)+          ]+      thirdReview =+        object+          [ "kind" .= ("model" :: Text),+            "reviewer" .= ("Bo" :: Text),+            "reviewed_at" .= ("2026-13-45T99:99:99Z" :: Text),+            "document_timestamp" .= ("2026-07-29T17:00:00Z" :: Text),+            "scope" .= ("invalid" :: Text),+            "context" .= (["wrong"] :: [Text])+          ]+      reviewValues = toJSON [firstReview, String "not-a-record", thirdReview]+  concept <-+    profileConcept+      "reviewed/bad"+      [("type", String "Reviewed Concept"), ("reviews", reviewValues)]+      "# Bad\n"+  cid <- parseTestConceptId "reviewed/bad"+  let permissiveExpected =+        [ NestedElementNotRecord cid (FieldPath (FieldName "reviews" :| [ArrayIndex 1])) (String "not-a-record"),+          CardinalityMismatch cid (nestedTestPath 2 "context") Scalar (toJSON (["wrong"] :: [Text])),+          MissingNestedProfileField cid (nestedTestPath 2 "outcome") Nothing,+          ValueFormatMismatch cid (nestedTestPath 2 "reviewed_at") Rfc3339Utc (String "2026-13-45T99:99:99Z"),+          ValueNotInVocabulary cid (nestedTestPath 2 "scope") reviewScopes (String "invalid")+        ]+  assertEqual permissiveExpected (validateProfile PermissiveConformance compiled [concept])+  assertEqual+    [ NestedElementNotRecord cid (FieldPath (FieldName "reviews" :| [ArrayIndex 1])) (String "not-a-record"),+      CardinalityMismatch cid (nestedTestPath 2 "context") Scalar (toJSON (["wrong"] :: [Text])),+      MissingRecommendedNestedProfileField cid (nestedTestPath 2 "notes") Nothing,+      MissingNestedProfileField cid (nestedTestPath 2 "outcome") Nothing,+      ValueFormatMismatch cid (nestedTestPath 2 "reviewed_at") Rfc3339Utc (String "2026-13-45T99:99:99Z"),+      ValueNotInVocabulary cid (nestedTestPath 2 "scope") reviewScopes (String "invalid")+    ]+    (validateProfile StrictAuthoring compiled [concept])++nestedProfileWithRules :: Cardinality -> NestedRules -> Maybe NestedRules -> ProfileSpec+nestedProfileWithRules outerCardinality profileNested typeNested =+  ProfileSpec+    { name = "nested-merge",+      description = Nothing,+      guidance = Nothing,+      okfVersion = "0.1",+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required =+              [ requiredField "type",+                fieldRule "reviews" Nothing [] outerCardinality Nothing (Just profileNested) Nothing Nothing+              ],+            recommended = [],+            optional = []+          },+      allowUnknownTypes = False,+      allowUnknownFields = True,+      idField = Nothing,+      requireBundleVersion = Nothing,+      types =+        [ TypeRule+            { type_ = "Reviewed Concept",+              description = Nothing,+              guidance = Nothing,+              frontmatter =+                FrontmatterRules+                  { membershipConstraints = [],+                    uniqueValuesConstraints = [],+                    presenceConstraints = [],+                    timestampOrderConstraints = [],+                    required = maybe [] (\rules -> [fieldRule "reviews" Nothing [] Any Nothing (Just rules) Nothing Nothing]) typeNested,+                    recommended = [],+                    optional = []+                  },+              pathPattern = Nothing,+              resourceScheme = Nothing,+              requireSchemaSection = False,+              schemaColumns = [],+              idPrefix = Nothing+            }+        ]+    }++nestedReviewProfileSpec :: ProfileSpec+nestedReviewProfileSpec =+  nestedProfileWithRules Any nestedRules Nothing+  where+    nestedRules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required =+            [ nestedFieldRule "kind" Nothing ["human", "model"] Any Nothing Nothing Nothing,+              nestedFieldRule "reviewer" Nothing [] Scalar Nothing Nothing Nothing,+              nestedFieldRule "reviewed_at" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing,+              nestedFieldRule "document_timestamp" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing,+              nestedFieldRule "scope" Nothing reviewScopes Any Nothing Nothing Nothing,+              nestedFieldRule "outcome" Nothing ["approved", "changes-requested", "commented"] Any Nothing Nothing Nothing,+              nestedFieldRule "context" Nothing [] Scalar Nothing Nothing Nothing+            ],+          recommended = [nestedFieldRule "notes" Nothing [] Scalar Nothing Nothing Nothing],+          optional = []+        }++nestedTestPath :: Int -> Text -> FieldPath+nestedTestPath elementIndex key =+  FieldPath (FieldName "reviews" :| [ArrayIndex elementIndex, FieldName key])++-- | A profile whose single object-valued key carries the given member rules and+-- the given declared cardinality. Built with record syntax rather than the+-- positional 'fieldRule' helper precisely because @objectFields@ is the member+-- under test here.+objectProfileWithRules :: Text -> Cardinality -> Maybe NestedRules -> Maybe NestedRules -> ProfileSpec+objectProfileWithRules key declaredCardinality objectRules elementRules =+  ProfileSpec+    { name = "object-rules",+      description = Nothing,+      guidance = Nothing,+      okfVersion = "0.1",+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required =+              [ requiredField "type",+                FieldRule+                  { field = key,+                    description = Nothing,+                    allowedValues = [],+                    cardinality = declaredCardinality,+                    format = Nothing,+                    elementFields = elementRules,+                    objectFields = objectRules,+                    reference = Nothing,+                    path = Nothing,+                    when = Nothing,+                    uniqueBy = Nothing+                  }+              ],+            recommended = [],+            optional = []+          },+      allowUnknownTypes = True,+      allowUnknownFields = True,+      idField = Nothing,+      requireBundleVersion = Nothing,+      types = []+    }++-- | The member rules used by the object-rule tests: @by@ is demanded, @at@ is+-- recommended and must be an RFC3339 UTC timestamp.+provenanceMemberRules :: NestedRules+provenanceMemberRules =+  NestedRules+    { allowUnknownFields = True,+      presenceConstraints = [],+      timestampOrderConstraints = [],+      required = [nestedFieldRule "by" (Just "Who or what produced this content.") [] Any Nothing Nothing Nothing],+      recommended = [nestedFieldRule "at" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing],+      optional = []+    }++-- | Declaring @objectFields@ next to an explicit scalar or list cardinality is+-- incoherent — a mapping is neither — and is rejected at compile time in both+-- directions, mirroring 'ElementFieldsRequireList' for the opposite mistake.+testObjectFieldsRequireObjectShape :: Either Text ()+testObjectFieldsRequireObjectShape = do+  assertEqual+    (Left (ObjectFieldsRequireObjectShape Nothing (fieldPath "generated") List :| []))+    (compileProfile (objectProfileWithRules "generated" List (Just provenanceMemberRules) Nothing))+  assertEqual+    (Left (ObjectFieldsRequireObjectShape Nothing (fieldPath "generated") Scalar :| []))+    (compileProfile (objectProfileWithRules "generated" Scalar (Just provenanceMemberRules) Nothing))++-- | A rule that declares object members and no explicit cardinality is refined+-- to 'Object', the compiled-only cardinality that has no Dhall spelling, and its+-- members are reachable through the new accessor.+testCompileObjectRule :: Either Text ()+testCompileObjectRule = do+  compiled <-+    firstShow+      (compileProfile (objectProfileWithRules "generated" Any (Just provenanceMemberRules) Nothing))+  rule <- lookupBaseRule compiled "generated"+  assertEqual Object (fieldRuleCardinality rule)+  assertEqual Nothing (fieldRuleElementFields rule)+  case fieldRuleObjectFields rule of+    Nothing -> Left "expected compiled object member rules"+    Just members -> do+      assertEqual ["at", "by"] (Map.keys members)+      byRule <- maybe (Left "expected a rule for by") Right (Map.lookup "by" members)+      assertEqual+        (Just "Who or what produced this content.")+        (fieldRuleDescription byRule)+      assertEqual [RequiredField] (map presenceClauseRequirement (fieldRulePresenceClauses byRule))+      -- Depth-bounded: a member rule never itself carries a nested shape.+      assertEqual Nothing (fieldRuleObjectFields byRule)+      assertEqual Nothing (fieldRuleElementFields byRule)++-- | A rule declaring both shapes stays at 'Any' cardinality, which is what lets+-- either OKF v0.2 spelling of @verified@ satisfy it, and compiles the same+-- member rules under both accessors.+testCompileRecordOrListRule :: Either Text ()+testCompileRecordOrListRule = do+  compiled <-+    firstShow+      ( compileProfile+          (objectProfileWithRules "verified" Any (Just provenanceMemberRules) (Just provenanceMemberRules))+      )+  rule <- lookupBaseRule compiled "verified"+  assertEqual Any (fieldRuleCardinality rule)+  assertEqual (Just ["at", "by"]) (Map.keys <$> fieldRuleObjectFields rule)+  assertEqual (Just ["at", "by"]) (Map.keys <$> fieldRuleElementFields rule)++-- | A profile with one path rule on a top-level key, plus the given rules on the+-- same key at type scope, so scheme intersection across scopes is exercisable.+pathProfileWith :: Maybe PathReferenceRule -> Maybe FieldFormat -> Maybe HandleReferenceRule -> Maybe PathReferenceRule -> ProfileSpec+pathProfileWith profilePath declaredFormat handlePolicy typePath =+  ProfileSpec+    { name = "path-rules",+      description = Nothing,+      guidance = Nothing,+      okfVersion = "0.1",+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [requiredField "type"],+            recommended = [],+            -- Optional rather than required, so a concept that simply does not+            -- carry the key reports nothing and the tests below see only the+            -- value checks they are about. An optional rule is fully+            -- value-checked whenever it is present.+            optional =+              [ (requiredField "resource")+                  { format = declaredFormat,+                    reference = handlePolicy,+                    path = profilePath+                  }+              ]+          },+      allowUnknownTypes = True,+      allowUnknownFields = True,+      idField = if isJust handlePolicy then Just "docId" else Nothing,+      requireBundleVersion = Nothing,+      types =+        [ TypeRule+            { type_ = "Metric",+              description = Nothing,+              guidance = Nothing,+              frontmatter =+                FrontmatterRules+                  { membershipConstraints = [],+                    uniqueValuesConstraints = [],+                    presenceConstraints = [],+                    timestampOrderConstraints = [],+                    required = [],+                    recommended = [],+                    optional = [(requiredField "resource") {path = typePath}]+                  },+              pathPattern = Nothing,+              resourceScheme = Nothing,+              requireSchemaSection = False,+              schemaColumns = [],+              idPrefix = if isJust handlePolicy then Just "ADR" else Nothing+            }+        | isJust typePath || isJust handlePolicy+        ]+    }++-- | A profile whose @sources@ key is a list of records, each of which carries a+-- path rule on @resource@ — the OKF v0.2 §6.2 field the rule kind exists for,+-- and the one that was unreachable before nested path checking existed.+sourcesPathProfile :: [Text] -> ProfileSpec+sourcesPathProfile permittedSchemes =+  ProfileSpec+    { name = "sources-paths",+      description = Nothing,+      guidance = Nothing,+      okfVersion = "0.1",+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [requiredField "type"],+            recommended = [],+            -- Optional for the same reason 'pathProfileWith' is: the tests are+            -- about what a present value resolves to, not about presence.+            optional = [fieldRule "sources" Nothing [] List Nothing (Just memberRules) Nothing Nothing]+          },+      allowUnknownTypes = True,+      allowUnknownFields = True,+      idField = Nothing,+      requireBundleVersion = Nothing,+      types = []+    }+  where+    memberRules =+      NestedRules+        { allowUnknownFields = True,+          presenceConstraints = [],+          timestampOrderConstraints = [],+          required =+            [ (nestedFieldRule "resource" Nothing [] Any Nothing Nothing Nothing)+                { path = Just (PathReferenceRule permittedSchemes False)+                }+            ],+          recommended = [],+          optional = []+        }++-- | Compiling a path rule normalizes its scheme list exactly as a handle rule's+-- is — deduplicated case-insensitively and case-folded for storage — and the+-- result is reachable through the new accessor at top-level, nested, and object+-- scope. Nested reachability is the part with no precedent:+-- 'compileOptionalNestedFieldRule' previously hard-coded every reference member+-- to 'Nothing'.+testCompilePathRule :: Either Text ()+testCompilePathRule = do+  compiled <-+    firstShow+      (compileProfile (pathProfileWith (Just (PathReferenceRule ["HTTPS", "https", "mori"] True)) Nothing Nothing Nothing))+  rule <- lookupBaseRule compiled "resource"+  assertEqual (Just (PathReferenceRule ["https", "mori"] True)) (fieldRulePath rule)+  -- A path rule and a handle rule are different things and never both present.+  assertEqual Nothing (fieldRuleReference rule)+  nestedCompiled <- firstShow (compileProfile (sourcesPathProfile ["https"]))+  sourcesRule <- lookupBaseRule nestedCompiled "sources"+  case fieldRuleElementFields sourcesRule of+    Nothing -> Left "expected compiled element member rules for sources"+    Just members -> do+      memberRule <- maybe (Left "expected a rule for resource") Right (Map.lookup "resource" members)+      assertEqual (Just (PathReferenceRule ["https"] False)) (fieldRulePath memberRule)+      -- Nested rules stay depth-bounded and carry no handle policy at all.+      assertEqual Nothing (fieldRuleReference memberRule)++-- | A type-scope path rule narrows the profile-scope one rather than replacing+-- it: schemes intersect and @allowSelf@ combines with logical AND. Unlike+-- 'mergeReferenceRule' the merge is total, because a path policy has no+-- @localPrefix@ for two scopes to disagree about.+testMergePathRule :: Either Text ()+testMergePathRule = do+  compiled <-+    firstShow+      ( compileProfile+          ( pathProfileWith+              (Just (PathReferenceRule ["https", "mori"] True))+              Nothing+              Nothing+              (Just (PathReferenceRule ["mori", "ftp"] False))+          )+      )+  merged <- lookupCompiledRule "resource" (compiledProfileRulesForType compiled "Metric")+  assertEqual (Just (PathReferenceRule ["mori"] False)) (fieldRulePath merged)++-- | The three ways a path rule can be incoherent on its own. Two reuse the+-- handle-reference definition errors because the claim is identical; the third+-- is new, and cannot arise at nested scope where 'NestedFieldRule' carries no+-- handle policy.+testPathDefinitionErrors :: Either Text ()+testPathDefinitionErrors = do+  -- A value cannot be resolved as both a PREFIX-N handle and a §6.2 path.+  assertEqual+    (Left (PathReferenceWithHandleReference Nothing (fieldPath "resource") :| []))+    ( compileProfile+        ( pathProfileWith+            (Just (PathReferenceRule [] False))+            Nothing+            (Just (handleReferenceRule "ADR" [] False))+            Nothing+        )+    )+  -- A scheme that is not a legal URI scheme, at top-level scope.+  assertEqual+    (Left (InvalidExternalReferenceScheme Nothing (fieldPath "resource") "9nope" :| []))+    (compileProfile (pathProfileWith (Just (PathReferenceRule ["9nope"] False)) Nothing Nothing Nothing))+  -- The same mistake at nested scope, which the reference walk did not reach+  -- before this plan extended it.+  assertEqual+    (Left (InvalidExternalReferenceScheme Nothing (objectMemberPath "sources" "resource") "9nope" :| []))+    (compileProfile (sourcesPathProfile ["9nope"]))+  -- A named format would be checked against text the path rule is already+  -- interpreting structurally, and the two can contradict.+  assertEqual+    (Left (ReferenceWithFormat Nothing (fieldPath "resource") Uri :| []))+    (compileProfile (pathProfileWith (Just (PathReferenceRule [] False)) (Just Uri) Nothing Nothing))++-- | The five outcomes of checking one path value at top-level scope, plus the+-- two shapes that are accepted in silence. Every diagnostic carries the raw text+-- the author wrote rather than the collapsed path okf computed from it.+testValidatePathTopLevel :: Either Text ()+testValidatePathTopLevel = do+  compiled <-+    firstShow+      (compileProfile (pathProfileWith (Just (PathReferenceRule ["https"] False)) Nothing Nothing Nothing))+  cid <- parseTestConceptId "metrics/revenue"+  target <- profileConcept "references/policy" [("type", String "Reference")] "# Policy\n"+  let check value = do+        subject <-+          profileConcept+            "metrics/revenue"+            [("type", String "Metric"), ("resource", value)]+            "# Revenue\n"+        pure (validateProfile PermissiveConformance compiled [subject, target])+      resourcePath = fieldPath "resource"+  -- A bundle path naming a real concept, and a permitted external URL, are both+  -- silent.+  check (String "/references/policy.md") >>= assertEqual []+  check (String "../references/policy.md") >>= assertEqual []+  check (String "https://wiki.acme/revenue") >>= assertEqual []+  -- A path to a non-Markdown file is accepted without a check, because+  -- validateProfile is handed concepts and never looked. §6.3's own example.+  check (String "/references/attesters/revenue.py") >>= assertEqual []+  -- The four failures.+  check (String "/references/gone.md")+    >>= assertEqual [DanglingPathReference cid resourcePath "/references/gone.md"]+  check (String "ftp://files.acme/revenue.csv")+    >>= assertEqual [ExternalReferenceSchemeNotAllowed cid resourcePath "ftp" ["https"]]+  check (String "../../../etc/passwd")+    >>= assertEqual [PathEscapesBundle cid resourcePath "../../../etc/passwd"]+  check (String "   ")+    >>= assertEqual [MalformedPathReference cid resourcePath (String "   ")]+  -- A value that is not text at all is malformed rather than silently skipped.+  check (Bool True)+    >>= assertEqual [MalformedPathReference cid resourcePath (Bool True)]+  -- A path resolving to the concept that carries it, with allowSelf unset.+  check (String "/metrics/revenue.md")+    >>= assertEqual [SelfDocumentReference cid resourcePath "/metrics/revenue.md"]++-- | The core-versus-profile divergence, closed: 'validateProfileWith' resolves a+-- path naming a file that is not a concept, and 'validateProfile' still cannot+-- and still says nothing.+--+-- Run against a real directory because that is the only way to have an inventory+-- holding a file 'walkBundle' filters out. @dangling-frontmatter-path@ carries+-- both halves already: @non-markdown.md@ names a @.py@ that is there and+-- @dangling.md@ names a @.txt@ that is not.+--+-- Specification §6.3's example is exactly this shape, and+-- @docs\/adr\/13-the-references-convention-and-non-markdown-files.md@ records why+-- the silent answer is preserved rather than tightened: a caller with no+-- directory has not looked, and reporting a target it never checked would be a+-- claim okf cannot back.+testValidateProfileWithInventory :: IO (Either Text ())+testValidateProfileWithInventory = do+  root <- fixturePath "dangling-frontmatter-path"+  concepts <- readBundle root+  inventory <- readBundleInventory root+  pure+    ( do+        compiled <-+          firstShow+            ( compileProfile+                (pathProfileWith (Just (PathReferenceRule ["bigquery"] False)) Nothing Nothing Nothing)+            )+        danglingId <- firstShow (parseConceptId "dangling")+        specSpellingId <- firstShow (parseConceptId "computations/spec-spelling")+        let resourcePath = fieldPath "resource"+        -- With the full inventory: the missing .txt and the relative .py that+        -- resolves outside the bundle are both reported, and the .py that is+        -- really there is silent.+        assertEqual+          [ DanglingPathReference specSpellingId resourcePath "references/attesters/revenue.py",+            DanglingPathReference danglingId resourcePath "/references/deleted.txt"+          ]+          (validateProfileWith inventory PermissiveConformance compiled concepts)+        -- Without it: nothing at all, exactly as before this plan. Neither target+        -- is Markdown, so a concepts-only caller has not looked at either.+        assertEqual [] (validateProfile PermissiveConformance compiled concepts)+    )++-- | The specification §10 contract expressed as a house convention, run against+-- the bundle it was written for.+--+-- This is the descriptor @docs\/user\/profiles.md@ shows, and this test is what+-- stops that document's transcript from rotting: the descriptor must keep+-- compiling ('testFrozenFixturesCompile' lists it) and must keep reporting these+-- deviations and no others.+--+-- What it demonstrates is the boundary this whole initiative rests on. okf's core+-- enforces exactly §10.2's one REQUIRED field and §10.3's exactly-one rule;+-- everything below — that a parameter carry a @type@, that an executor be+-- declared at all — is a team's own policy, reached with @objectFields@ for the+-- mapping-valued keys and @elementFields@ for the list-valued one, and scoped to+-- one @type@ with a 'TypeRule' so no @Metric@ in the bundle is asked for a+-- @runtime@.+--+-- @computations\/churn@ is the concept that makes the point: it produces no core+-- diagnostic at all and one deviation here.+testAttestedComputationHouseProfile :: IO (Either Text ())+testAttestedComputationHouseProfile = do+  descriptorPath <- fixtureFilePath "profiles/attested-computation-house.dhall"+  loaded <- loadProfileFile descriptorPath+  root <- fixturePath "attested-computation"+  concepts <- readBundle root+  inventory <- readBundleInventory root+  pure $ case loaded of+    Left err -> Left ("failed to load the house attested computation profile: " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      bothId <- firstShow (parseConceptId "computations/both-computations")+      churnId <- firstShow (parseConceptId "computations/churn")+      marginId <- firstShow (parseConceptId "computations/margin")+      noneId <- firstShow (parseConceptId "computations/no-computation")+      twoBlocksId <- firstShow (parseConceptId "computations/two-blocks")+      -- Only the required rules fire in permissive mode. `computations/revenue`+      -- carries the whole contract and is absent from both lists.+      assertEqual+        [ MissingProfileField bothId "executor" Nothing,+          MissingProfileField bothId "parameters" Nothing,+          MissingNestedProfileField churnId parameterTypePath Nothing,+          MissingProfileField marginId "executor" Nothing,+          MissingProfileField noneId "executor" Nothing,+          MissingProfileField noneId "parameters" Nothing,+          MissingProfileField twoBlocksId "executor" Nothing,+          MissingProfileField twoBlocksId "parameters" Nothing+        ]+        (validateProfileWith inventory PermissiveConformance compiled concepts)+      -- Under strict the recommended rules join them, including the nested+      -- `executor.receipt` on the one concept that declares an executor without+      -- one. No path deviation appears in either list: every path-valued field in+      -- this bundle resolves.+      assertEqual+        [ MissingRecommendedProfileField bothId "attester" Nothing,+          MissingProfileField bothId "executor" Nothing,+          MissingProfileField bothId "parameters" Nothing,+          MissingRecommendedProfileField churnId "attester" Nothing,+          MissingRecommendedNestedProfileField churnId executorReceiptPath Nothing,+          MissingNestedProfileField churnId parameterTypePath Nothing,+          MissingRecommendedProfileField marginId "attester" Nothing,+          MissingProfileField marginId "executor" Nothing,+          MissingRecommendedProfileField noneId "attester" Nothing,+          MissingProfileField noneId "executor" Nothing,+          MissingProfileField noneId "parameters" Nothing,+          MissingRecommendedProfileField twoBlocksId "attester" Nothing,+          MissingProfileField twoBlocksId "executor" Nothing,+          MissingProfileField twoBlocksId "parameters" Nothing+        ]+        (validateProfileWith inventory StrictAuthoring compiled concepts)+  where+    parameterTypePath = FieldPath (FieldName "parameters" :| [ArrayIndex 0, FieldName "type"])+    executorReceiptPath = FieldPath (FieldName "executor" :| [FieldName "receipt"])++-- | The motivating case: a path rule on @sources[].resource@, reported with the+-- element index so the author can find the entry. Nested path checking did not+-- exist before this plan — 'NestedFieldRule' had no reference member of any kind+-- — so this is the assertion the whole plan is for.+testValidatePathNested :: Either Text ()+testValidatePathNested = do+  compiled <- firstShow (compileProfile (sourcesPathProfile ["https"]))+  cid <- parseTestConceptId "metric"+  target <- profileConcept "references/policy" [("type", String "Reference")] "# Policy\n"+  subject <-+    profileConcept+      "metric"+      [ ("type", String "Metric"),+        ( "sources",+          toJSON+            [ object ["id" .= ("policy" :: Text), "resource" .= ("/references/policy.md" :: Text)],+              object ["id" .= ("gone" :: Text), "resource" .= ("/references/gone.md" :: Text)],+              object ["id" .= ("upstream" :: Text), "resource" .= ("https://wiki.acme/revenue" :: Text)],+              object ["id" .= ("ftp" :: Text), "resource" .= ("ftp://files.acme/revenue.csv" :: Text)],+              object ["id" .= ("escape" :: Text), "resource" .= ("../../etc/passwd" :: Text)],+              object ["id" .= ("script" :: Text), "resource" .= ("references/attesters/revenue.py" :: Text)]+            ]+        )+      ]+      "# Revenue\n"+  assertEqual+    [ DanglingPathReference cid (nestedTestPathIn "sources" 1 "resource") "/references/gone.md",+      ExternalReferenceSchemeNotAllowed cid (nestedTestPathIn "sources" 3 "resource") "ftp" ["https"],+      PathEscapesBundle cid (nestedTestPathIn "sources" 4 "resource") "../../etc/passwd"+    ]+    (validateProfile PermissiveConformance compiled [subject, target])++-- | The same rule kind at object scope, where the member is named without an+-- index: @executor.resource@ rather than @executor[0].resource@.+testValidatePathObjectScope :: Either Text ()+testValidatePathObjectScope = do+  compiled <-+    firstShow+      ( compileProfile+          ( objectProfileWithRules+              "executor"+              Any+              ( Just+                  NestedRules+                    { allowUnknownFields = True,+                      presenceConstraints = [],+                      timestampOrderConstraints = [],+                      required =+                        [ (nestedFieldRule "resource" Nothing [] Any Nothing Nothing Nothing)+                            { path = Just (PathReferenceRule [] False)+                            }+                        ],+                      recommended = [],+                      optional = []+                    }+              )+              Nothing+          )+      )+  cid <- parseTestConceptId "thing"+  subject <-+    profileConcept+      "thing"+      [("type", String "Thing"), ("executor", object ["resource" .= ("/computations/gone.md" :: Text)])]+      "# Thing\n"+  assertEqual+    [DanglingPathReference cid (objectMemberPath "executor" "resource") "/computations/gone.md"]+    (validateProfile PermissiveConformance compiled [subject])++nestedTestPathIn :: Text -> Int -> Text -> FieldPath+nestedTestPathIn parent elementIndex key =+  FieldPath (FieldName parent :| [ArrayIndex elementIndex, FieldName key])++-- | A profile declaring the given @okfVersion@, with the given rules in the+-- given presence list, so the version checks can be exercised in one shape.+versionProfileWith :: Text -> Text -> [FieldRule] -> ProfileSpec+versionProfileWith declaredVersion listName rules =+  ProfileSpec+    { name = "versioned",+      description = Nothing,+      guidance = Nothing,+      okfVersion = declaredVersion,+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [requiredField "type"] <> [rule | rule <- rules, listName == "required"],+            recommended = [rule | rule <- rules, listName == "recommended"],+            optional = [rule | rule <- rules, listName == "optional"]+          },+      allowUnknownTypes = True,+      allowUnknownFields = True,+      idField = Nothing,+      requireBundleVersion = Nothing,+      types = []+    }++-- | An @okfVersion@ okf cannot read at all, and one naming a major version okf+-- does not implement. The second deliberately diverges from the bundle-side rule+-- of specification §12: a bundle may come from a third party and is read+-- best-effort, while a profile is an instruction to okf whose author is present.+testProfileVersionParsing :: Either Text ()+testProfileVersionParsing = do+  assertEqual+    (Left (InvalidProfileOkfVersion "banana" :| []))+    (compileProfile (versionProfileWith "banana" "optional" []))+  assertEqual+    (Left (ProfileOkfVersionNotUnderstood "1.0" :| []))+    (compileProfile (versionProfileWith "1.0" "optional" []))++-- | A higher /minor/ within a known major is clamped rather than rejected,+-- mirroring 'Okf.Validation.versionGate': §12 defines a minor bump as+-- backward-compatible additions, so a v0.9 profile expresses only rules okf+-- already understands. The clamp is observable through the diagnostic, which+-- names the effective version rather than the declared one.+testProfileVersionMinorClamp :: Either Text ()+testProfileVersionMinorClamp = do+  let timestampRule = fieldRule "timestamp" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing Nothing+  assertEqual+    (Left (FieldSupersededInOkfVersion Nothing (fieldPath "timestamp") "0.2" "0.2" :| []))+    (compileProfile (versionProfileWith "0.9" "recommended" [timestampRule]))+  -- And a v0.9 profile that names nothing version-specific simply compiles.+  case compileProfile (versionProfileWith "0.9" "optional" []) of+    Left errs -> Left ("expected a v0.9 profile to compile, got " <> Text.pack (show (toList errs)))+    Right _ -> Right ()++-- | A profile that demands a bundle version okf cannot parse is rejected at+-- compile time, before any bundle is read: no declaration could ever be compared+-- against it, so the descriptor is asking for something unanswerable.+--+-- An unknown /major/ is deliberately accepted here, unlike in @okfVersion@. There+-- the profile asks okf to interpret rules it may not understand; here it states a+-- minimum that a bundle's own declaration is compared against, which stays+-- meaningful whatever the major is.+testRequiredBundleVersionParsing :: Either Text ()+testRequiredBundleVersionParsing = do+  assertEqual+    (Left (InvalidRequiredBundleVersion "banana" :| []))+    (compileProfile (requireBundleVersionProfile (Just "banana")))+  for_ [Just "0.2", Just "1.0", Nothing] $ \required ->+    case compileProfile (requireBundleVersionProfile required) of+      Left errs -> Left ("expected a clean compile, got " <> Text.pack (show (toList errs)))+      Right _ -> Right ()++-- | What each shape of a bundle's §12 declaration means against a profile that+-- requires 0.2. A bundle ahead of the minimum is not a deviation; one behind it,+-- one that says nothing, and one okf cannot parse all are.+testValidateProfileVersion :: Either Text ()+testValidateProfileVersion = do+  compiled <- firstShow (compileProfile (requireBundleVersionProfile (Just "0.2")))+  assertEqual [] (validateProfileVersion (VersionDeclared (OkfVersion 0 2)) compiled)+  assertEqual [] (validateProfileVersion (VersionDeclared (OkfVersion 0 3)) compiled)+  assertEqual [] (validateProfileVersion (VersionDeclared (OkfVersion 1 0)) compiled)+  assertEqual+    [RequiredBundleVersionUnmet "0.2" (Just "0.1")]+    (validateProfileVersion (VersionDeclared (OkfVersion 0 1)) compiled)+  assertEqual+    [RequiredBundleVersionUnmet "0.2" Nothing]+    (validateProfileVersion VersionUndeclared compiled)+  assertEqual+    [RequiredBundleVersionUnmet "0.2" (Just "banana")]+    (validateProfileVersion (VersionUnparseable "banana") compiled)++-- | The default is inert: a profile that requires nothing reports nothing,+-- whatever the bundle declares. Almost every profile is this one.+testValidateProfileVersionUnrequired :: Either Text ()+testValidateProfileVersionUnrequired = do+  compiled <- firstShow (compileProfile (requireBundleVersionProfile Nothing))+  assertEqual Nothing (compiledProfileRequiredBundleVersion compiled)+  for_+    [ VersionDeclared (OkfVersion 0 1),+      VersionDeclared (OkfVersion 0 2),+      VersionUnparseable "banana",+      VersionUndeclared+    ]+    (\declaration -> assertEqual [] (validateProfileVersion declaration compiled))++-- | A minimal v0.2 profile whose only interesting member is the requirement under+-- test.+requireBundleVersionProfile :: Maybe Text -> ProfileSpec+requireBundleVersionProfile required =+  (versionProfileWith "0.2" "optional" []) {requireBundleVersion = required}++-- | A key the declared version supersedes is an error where it is /demanded/ and+-- legal where it is merely documented. The optional list is how a team migrating+-- a corpus says "tolerated but not demanded", and making it an error everywhere+-- would leave no way to describe a migration.+testProfileVersionSupersededField :: Either Text ()+testProfileVersionSupersededField = do+  let timestampRule = fieldRule "timestamp" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing Nothing+      superseded = FieldSupersededInOkfVersion Nothing (fieldPath "timestamp") "0.2" "0.2"+  assertEqual+    (Left (superseded :| []))+    (compileProfile (versionProfileWith "0.2" "required" [timestampRule]))+  assertEqual+    (Left (superseded :| []))+    (compileProfile (versionProfileWith "0.2" "recommended" [timestampRule]))+  -- The migration shape, and the v0.1 profile that has no reason to be told+  -- anything at all.+  for_ [versionProfileWith "0.2" "optional" [timestampRule], versionProfileWith "0.1" "required" [timestampRule]] $ \spec ->+    case compileProfile spec of+      Left errs -> Left ("expected a clean compile, got " <> Text.pack (show (toList errs)))+      Right _ -> Right ()++-- | The actor formats encode the specification §7 convention v0.2 introduced, so+-- naming one under a v0.1 declaration is incoherent. A format is an okf+-- descriptor feature rather than a key name, which is exactly why this check is+-- safe where the mirror check on key names is not — see+-- 'testProfileVersionDoesNotJudgeKeyNames'.+testProfileVersionActorFormat :: Either Text ()+testProfileVersionActorFormat = do+  let actorRule = fieldRule "author" Nothing [] Any (Just Actor) Nothing Nothing Nothing+      humanRule = fieldRule "author" Nothing [] Any (Just Profile.HumanActor) Nothing Nothing Nothing+  assertEqual+    (Left (FormatRequiresOkfVersion Nothing (fieldPath "author") Actor "0.1" "0.2" :| []))+    (compileProfile (versionProfileWith "0.1" "optional" [actorRule]))+  assertEqual+    (Left (FormatRequiresOkfVersion Nothing (fieldPath "author") Profile.HumanActor "0.1" "0.2" :| []))+    (compileProfile (versionProfileWith "0.1" "optional" [humanRule]))+  -- The same rule under a v0.2 declaration is exactly what the format is for.+  case compileProfile (versionProfileWith "0.2" "optional" [actorRule]) of+    Left errs -> Left ("expected a v0.2 actor rule to compile, got " <> Text.pack (show (toList errs)))+    Right _ -> Right ()++-- | The check okf deliberately does /not/ perform, asserted so it is not added+-- back by someone who thinks it was forgotten.+--+-- A v0.1 profile constraining its own @status@, @sources@, or @verified@ key is+-- coherent: per @docs\/adr\/1-profile-declared-document-ids.md@ constraining keys+-- the core format does not own is what profiles are /for/, and these are ordinary+-- words teams were already using before v0.2 claimed them. Rejecting+-- @field.enum "status" ["proposed", "accepted"]@ for naming an ADR lifecycle+-- would be a false positive on a descriptor okf cannot see.+testProfileVersionDoesNotJudgeKeyNames :: Either Text ()+testProfileVersionDoesNotJudgeKeyNames =+  for_ ["status", "sources", "verified", "generated", "stale_after", "usage_window"] $ \key ->+    let houseRule = fieldRule key Nothing ["proposed", "accepted"] Any Nothing Nothing Nothing Nothing+     in case compileProfile (versionProfileWith "0.1" "optional" [houseRule]) of+          Left errs ->+            Left ("a v0.1 profile naming " <> key <> " should compile, got " <> Text.pack (show (toList errs)))+          Right _ -> Right ()++lookupBaseRule :: CompiledProfile -> Text -> Either Text EffectiveFieldRule+lookupBaseRule compiled key =+  maybe+    (Left ("expected a compiled rule for " <> key))+    Right+    (Map.lookup key (compiledProfileBaseRules compiled))++reviewScopes :: [Text]+reviewScopes = ["content", "technical-accuracy", "editorial", "catalog-metadata", "content-and-metadata"]++testConditionDefinitionErrors :: Either Text ()+testConditionDefinitionErrors = do+  let source key values sourceCardinality =+        fieldRule key Nothing values sourceCardinality Nothing Nothing Nothing Nothing+      target key sourceKey values =+        fieldRule key Nothing [] Any Nothing Nothing Nothing (Just (FieldCondition sourceKey values))+      compileWith rules =+        compileProfile+          typeAwareProfileSpec+            { frontmatter = FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = rules, recommended = [], optional = []},+              allowUnknownTypes = True,+              types = []+            }+      targetPath key = fieldPath key+  assertEqual+    (Left (EmptyConditionValues Nothing (targetPath "target") (targetPath "status") :| []))+    (compileWith [source "status" ["active"] Scalar, target "target" "status" []])+  assertEqual+    (Left (ConditionFieldNotDeclared Nothing (targetPath "target") (targetPath "missing") :| []))+    (compileWith [target "target" "missing" ["active"]])+  assertEqual+    (Left (ConditionFieldNotScalar Nothing (targetPath "target") (targetPath "status") List :| []))+    (compileWith [source "status" ["active"] List, target "target" "status" ["active"]])+  assertEqual+    (Left (ConditionFieldOpenVocabulary Nothing (targetPath "target") (targetPath "status") :| []))+    (compileWith [source "status" [] Scalar, target "target" "status" ["active"]])+  assertEqual+    (Left (ConditionFieldHasUnreachableValues Nothing (targetPath "target") (targetPath "status") ["superseded"] ["active"] :| []))+    (compileWith [source "status" ["active"] Scalar, target "target" "status" ["superseded"]])+  assertEqual+    (Left (SelfConditionalField Nothing (targetPath "status") :| []))+    (compileWith [fieldRule "status" Nothing ["active"] Scalar Nothing Nothing Nothing (Just (FieldCondition "status" ["active"]))])+  let nestedCrossScope =+        NestedRules+          { allowUnknownFields = True,+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required =+              [ nestedFieldRule "kind" Nothing ["human", "model"] Scalar Nothing Nothing Nothing,+                nestedFieldRule "provider" Nothing [] Scalar Nothing Nothing (Just (FieldCondition "status" ["active"]))+              ],+            recommended = [],+            optional = []+          }+      crossScopeProfile =+        typeAwareProfileSpec+          { frontmatter =+              FrontmatterRules+                { membershipConstraints = [],+                  uniqueValuesConstraints = [],+                  presenceConstraints = [],+                  timestampOrderConstraints = [],+                  required =+                    [ source "status" ["active"] Scalar,+                      fieldRule "reviews" Nothing [] List Nothing (Just nestedCrossScope) Nothing Nothing+                    ],+                  recommended = [],+                  optional = []+                },+            allowUnknownTypes = True,+            types = []+          }+  assertEqual+    (Left (ConditionFieldNotDeclared Nothing (nestedDefinitionTestPath "reviews" "provider") (nestedDefinitionTestPath "reviews" "status") :| []))+    (compileProfile crossScopeProfile)+  where+    nestedDefinitionTestPath parent child =+      FieldPath (FieldName parent :| [FieldName child])++testTopLevelConditionalPresence :: Either Text ()+testTopLevelConditionalPresence = do+  let statusRule = fieldRule "status" Nothing ["active", "superseded"] Scalar Nothing Nothing Nothing Nothing+      recommendedTarget =+        fieldRule "supersededBy" Nothing ["ADR-1"] Scalar Nothing Nothing Nothing (Just (FieldCondition "status" ["active"]))+      requiredTarget =+        fieldRule "supersededBy" Nothing ["ADR-1"] Scalar Nothing Nothing Nothing (Just (FieldCondition "status" ["superseded"]))+      base =+        typeAwareProfileSpec+          { frontmatter = FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [requiredField "type", statusRule], recommended = [recommendedTarget], optional = []},+            allowUnknownTypes = True,+            types =+              [ withTypeFrontmatter+                  FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [requiredTarget], recommended = [], optional = []}+                  (firstTypeRule typeAwareProfileSpec)+              ]+          }+  compiled <- firstShow (compileProfile base)+  active <- profileConcept "active" [("type", String "Owned Concept"), ("status", String "active")] "# Active\n"+  superseded <- profileConcept "superseded" [("type", String "Owned Concept"), ("status", String "superseded")] "# Superseded\n"+  invalidPresent <- profileConcept "invalid-present" [("type", String "Owned Concept"), ("status", String "active"), ("supersededBy", String "ADR-2")] "# Invalid\n"+  missingSource <- profileConcept "missing-source" [("type", String "Owned Concept")] "# Missing source\n"+  invalidSource <- profileConcept "invalid-source" [("type", String "Owned Concept"), ("status", String "unknown")] "# Invalid source\n"+  wrongShapeSource <- profileConcept "wrong-shape-source" [("type", String "Owned Concept"), ("status", toJSON (["active"] :: [Text]))] "# Wrong shape\n"+  activeId <- parseTestConceptId "active"+  supersededId <- parseTestConceptId "superseded"+  invalidId <- parseTestConceptId "invalid-present"+  missingSourceId <- parseTestConceptId "missing-source"+  invalidSourceId <- parseTestConceptId "invalid-source"+  wrongShapeSourceId <- parseTestConceptId "wrong-shape-source"+  assertEqual [] (validateProfile PermissiveConformance compiled [active])+  assertEqual+    [MissingRecommendedProfileField activeId "supersededBy" (Just (FieldCondition "status" ["active"]))]+    (validateProfile StrictAuthoring compiled [active])+  assertEqual+    [MissingProfileField supersededId "supersededBy" (Just (FieldCondition "status" ["superseded"]))]+    (validateProfile PermissiveConformance compiled [superseded])+  assertEqual+    [ValueNotInVocabulary invalidId (fieldPath "supersededBy") ["ADR-1"] (String "ADR-2")]+    (validateProfile PermissiveConformance compiled [invalidPresent])+  assertEqual+    [MissingProfileField missingSourceId "status" Nothing]+    (validateProfile PermissiveConformance compiled [missingSource])+  assertEqual+    [ValueNotInVocabulary invalidSourceId (fieldPath "status") ["active", "superseded"] (String "unknown")]+    (validateProfile PermissiveConformance compiled [invalidSource])+  assertEqual+    [CardinalityMismatch wrongShapeSourceId (fieldPath "status") Scalar (toJSON (["active"] :: [Text]))]+    (validateProfile PermissiveConformance compiled [wrongShapeSource])++testNestedConditionalPresence :: Either Text ()+testNestedConditionalPresence = do+  let nestedRules =+        NestedRules+          { allowUnknownFields = True,+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required =+              [ nestedFieldRule "kind" Nothing ["human", "model"] Scalar Nothing Nothing Nothing,+                nestedFieldRule "provider" Nothing [] Scalar Nothing Nothing (Just (FieldCondition "kind" ["model"]))+              ],+            recommended =+              [nestedFieldRule "notes" Nothing [] Scalar Nothing Nothing (Just (FieldCondition "kind" ["human"]))],+            optional = []+          }+      spec = nestedProfileWithRules List nestedRules Nothing+  compiled <- firstShow (compileProfile spec)+  concept <-+    profileConcept+      "conditional-reviews"+      [ ("type", String "Reviewed Concept"),+        ("reviews", toJSON [object ["kind" .= ("model" :: Text)], object ["kind" .= ("human" :: Text)], object []])+      ]+      "# Conditional reviews\n"+  cid <- parseTestConceptId "conditional-reviews"+  assertEqual+    [MissingNestedProfileField cid (nestedTestPath 0 "provider") (Just (FieldCondition "kind" ["model"])), MissingNestedProfileField cid (nestedTestPath 2 "kind") Nothing]+    (validateProfile PermissiveConformance compiled [concept])+  assertEqual+    [ MissingNestedProfileField cid (nestedTestPath 0 "provider") (Just (FieldCondition "kind" ["model"])),+      MissingRecommendedNestedProfileField cid (nestedTestPath 1 "notes") (Just (FieldCondition "kind" ["human"])),+      MissingNestedProfileField cid (nestedTestPath 2 "kind") Nothing+    ]+    (validateProfile StrictAuthoring compiled [concept])++testReferenceDefinitionErrors :: Either Text ()+testReferenceDefinitionErrors = do+  let referenceRule key prefix schemes fieldFormat =+        fieldRule+          key+          Nothing+          []+          Scalar+          fieldFormat+          Nothing+          (Just (handleReferenceRule prefix schemes False))+          Nothing+      baseType = firstTypeRule testDocumentIdProfileSpec+      specWith profileIdField typeRules profileRules =+        testDocumentIdProfileSpec+          { frontmatter = FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = profileRules, recommended = [], optional = []},+            idField = profileIdField,+            requireBundleVersion = Nothing,+            types = typeRules+          }+      path = fieldPath "supersedes"+      invalidPrefixType = baseType {idPrefix = Just "1ADR"}+      invalidPrefixSpec = specWith (Just "docId") [invalidPrefixType] [referenceRule "supersedes" "1ADR" [] Nothing]+      undeclaredPrefixSpec = specWith (Just "docId") [baseType] [referenceRule "supersedes" "PAT" [] Nothing]+      missingIdFieldSpec = specWith Nothing [baseType] [referenceRule "supersedes" "ADR" [] Nothing]+      invalidSchemeSpec = specWith (Just "docId") [baseType] [referenceRule "supersedes" "ADR" ["mori_", "MORI_"] Nothing]+      formatSpec = specWith (Just "docId") [baseType] [referenceRule "supersedes" "ADR" [] (Just (DocumentHandle "ADR"))]+      typeReference = referenceRule "supersedes" "RFC" [] Nothing+      conflictingType :: TypeRule+      conflictingType = baseType & #frontmatter .~ FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [typeReference], recommended = [], optional = []}+      rfcType = baseType {type_ = "RFC", idPrefix = Just "RFC", pathPattern = Nothing}+      conflictSpec = specWith (Just "docId") [conflictingType, rfcType] [referenceRule "supersedes" "ADR" [] Nothing]+  assertEqual+    (Left (InvalidReferencePrefix Nothing path "1ADR" :| []))+    (compileProfile invalidPrefixSpec)+  assertEqual+    (Left (ReferencePrefixNotDeclared Nothing path "PAT" :| []))+    (compileProfile undeclaredPrefixSpec)+  assertEqual+    (Left (ReferenceRequiresIdField Nothing path :| []))+    (compileProfile missingIdFieldSpec)+  assertEqual+    (Left (InvalidExternalReferenceScheme Nothing path "mori_" :| []))+    (compileProfile invalidSchemeSpec)+  assertEqual+    (Left (ReferenceWithFormat Nothing path (DocumentHandle "ADR") :| []))+    (compileProfile formatSpec)+  assertEqual+    (Left (ConflictingReferencePrefix "Decision Record" path "ADR" "RFC" :| []))+    (compileProfile conflictSpec)++testCompileNestedReferenceAndUniqueness :: IO (Either Text ())+testCompileNestedReferenceAndUniqueness = do+  loaded <- loadNestedReferenceSpec+  pure $ do+    spec <- loaded+    compiled <- firstShow (compileProfile spec)+    dependencies <- lookupBaseRule compiled "dependencies"+    acceptanceCriteria <- lookupBaseRule compiled "acceptanceCriteria"+    assertEqual (Just "id") (fieldRuleUniqueBy acceptanceCriteria)+    case fieldRuleElementFields dependencies >>= Map.lookup "ref" of+      Nothing -> Left "expected a compiled dependencies.ref rule"+      Just referenceRule ->+        assertEqual+          ( Just+              ( HandleReferenceRule+                  "IR"+                  ["mori"]+                  False+                  False+                  (Just nestedReferencePattern)+              )+          )+          (fieldRuleReference referenceRule)++testNestedReferenceAndUniquenessValidation :: IO (Either Text ())+testNestedReferenceAndUniquenessValidation = do+  loaded <- loadNestedReferenceSpec+  validRoot <- fixturePath "profile-nested-references-and-uniqueness-valid"+  invalidRoot <- fixturePath "profile-nested-references-and-uniqueness-invalid"+  validConcepts <- readBundle validRoot+  invalidConcepts <- readBundle invalidRoot+  pure $ do+    spec <- loaded+    compiled <- firstShow (compileProfile spec)+    assertEqual [] (validateProfile PermissiveConformance compiled validConcepts)+    duplicateId <- parseTestConceptId "requests/duplicate"+    assertEqual+      [DuplicateNestedFieldValue duplicateId (objectMemberPath "acceptanceCriteria" "id") (String "AC-1") (0 :| [1])]+      (validateProfile PermissiveConformance compiled invalidConcepts)+    assertReferenceCase compiled "local" "IR-1" (LocalDocumentReferenceNotAllowed <$> pureCaseId "local" <*> pure (nestedTestPathFor "dependencies" 0 "ref") <*> pure "IR-1")+    assertReferenceCase compiled "scheme" "https://example.test/IR-1" (ExternalReferenceSchemeNotAllowed <$> pureCaseId "scheme" <*> pure (nestedTestPathFor "dependencies" 0 "ref") <*> pure "https" <*> pure ["mori"])+    assertPatternCase compiled "artifact-kind" "mori://namespace/project/okf/decisions/concepts/IR-1"+    assertPatternCase compiled "leading-zero" "mori://namespace/project/okf/improvement-requests/concepts/IR-01"+    assertPatternCase compiled "query" "mori://namespace/project/okf/improvement-requests/concepts/IR-1?x=1"+    assertPatternCase compiled "fragment" "mori://namespace/project/okf/improvement-requests/concepts/IR-1#x"+    malformed <- referenceConcept "malformed" "not a reference" ["AC-1", "AC-2"]+    malformedId <- parseTestConceptId "requests/malformed"+    assertEqual+      [MalformedDocumentReference malformedId (nestedTestPathFor "dependencies" 0 "ref") (String "not a reference")]+      (validateProfile PermissiveConformance compiled [malformed])+    grouped <- referenceConcept "groups" canonicalNestedReference ["AC-1", "AC-2", "AC-1", "AC-2"]+    groupedId <- parseTestConceptId "requests/groups"+    assertEqual+      [ DuplicateNestedFieldValue groupedId (objectMemberPath "acceptanceCriteria" "id") (String "AC-1") (0 :| [2]),+        DuplicateNestedFieldValue groupedId (objectMemberPath "acceptanceCriteria" "id") (String "AC-2") (1 :| [3])+      ]+      (validateProfile PermissiveConformance compiled [grouped])+  where+    pureCaseId name = parseTestConceptId ("requests/" <> name)++    assertReferenceCase compiled name raw expectedAction = do+      concept <- referenceConcept name raw ["AC-1", "AC-2"]+      expected <- expectedAction+      assertEqual [expected] (validateProfile PermissiveConformance compiled [concept])++    assertPatternCase compiled name raw = do+      cid <- parseTestConceptId ("requests/" <> name)+      assertReferenceCase+        compiled+        name+        raw+        (Right (ExternalReferencePatternMismatch cid (nestedTestPathFor "dependencies" 0 "ref") raw nestedReferencePattern))++testNestedReferenceAndUniquenessDefinitionErrors :: IO (Either Text ())+testNestedReferenceAndUniquenessDefinitionErrors = do+  loaded <- loadNestedReferenceSpec+  pure $ do+    spec <- loaded+    dependencies <- lookupRaw "dependencies" spec+    acceptance <- lookupRaw "acceptanceCriteria" spec+    let invalidPattern = updateNestedRule "ref" (\rule -> rule {reference = setPattern "[" <$> rule ^. #reference}) dependencies+        invalidPatternSpec = replaceBaseRule invalidPattern spec+    assertSingleDefinitionError+      (\case InvalidExternalUriPattern Nothing path "[" _ -> path == objectMemberPath "dependencies" "ref"; _ -> False)+      (compileProfile invalidPatternSpec)++    let typePattern = updateNestedRule "ref" (\rule -> rule {reference = setPattern "mori://different" <$> rule ^. #reference}) dependencies+        patternConflictSpec = addTypeRule typePattern spec+    assertSingleDefinitionError+      (== ConflictingExternalUriPatterns "Improvement Request" (objectMemberPath "dependencies" "ref") nestedReferencePattern "mori://different")+      (compileProfile patternConflictSpec)++    let noElements = (requiredField "plainRecords") {uniqueBy = Just "id"}+    assertSingleDefinitionError+      (== UniqueByRequiresElementFields Nothing (fieldPath "plainRecords") "id")+      (compileProfile (replaceBaseRule noElements spec))++    let missingMember = acceptance {uniqueBy = Just "missing"}+    assertSingleDefinitionError+      (== UniqueByFieldNotDeclared Nothing (objectMemberPath "acceptanceCriteria" "missing"))+      (compileProfile (replaceBaseRule missingMember spec))++    let optionalMember = updateNestedPresence "id" acceptance+    assertSingleDefinitionError+      (== UniqueByFieldNotUnconditionallyRequired Nothing (objectMemberPath "acceptanceCriteria" "id"))+      (compileProfile (replaceBaseRule optionalMember spec))++    let listMember = updateNestedRule "id" (\rule -> rule {cardinality = List}) acceptance+    assertSingleDefinitionError+      (== UniqueByFieldNotScalar Nothing (objectMemberPath "acceptanceCriteria" "id") List)+      (compileProfile (replaceBaseRule listMember spec))++    let conflictingUnique = acceptance {uniqueBy = Just "text"}+    assertSingleDefinitionError+      (== ConflictingUniqueBy "Improvement Request" (fieldPath "acceptanceCriteria") "id" "text")+      (compileProfile (addTypeRule conflictingUnique spec))+  where+    setPattern :: Text -> HandleReferenceRule -> HandleReferenceRule+    setPattern patternText policy = policy {externalUriPattern = Just patternText}++    lookupRaw :: Text -> ProfileSpec -> Either Text FieldRule+    lookupRaw key spec =+      case [rule | rule <- spec ^. #frontmatter . #required, rule ^. #field == key] of+        [rule] -> Right rule+        _ -> Left ("expected one raw rule for " <> key)++    replaceBaseRule :: FieldRule -> ProfileSpec -> ProfileSpec+    replaceBaseRule replacement spec =+      spec+        { frontmatter =+            (spec ^. #frontmatter)+              { required = replacement : filter ((/= replacement ^. #field) . (^. #field)) (spec ^. #frontmatter . #required)+              }+        }++    addTypeRule :: FieldRule -> ProfileSpec -> ProfileSpec+    addTypeRule typeField spec =+      spec+        { types =+            [ typeRule+                { frontmatter = FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [typeField], recommended = [], optional = []}+                }+            | typeRule <- spec ^. #types+            ]+        }++    updateNestedRule :: Text -> (NestedFieldRule -> NestedFieldRule) -> FieldRule -> FieldRule+    updateNestedRule key change parent =+      parent {elementFields = updateRules <$> parent ^. #elementFields}+      where+        updateRules :: NestedRules -> NestedRules+        updateRules rules =+          rules+            { required = map update (rules ^. #required),+              recommended = map update (rules ^. #recommended),+              optional = map update (rules ^. #optional)+            }+        update rule | rule ^. #field == key = change rule+        update rule = rule++    updateNestedPresence :: Text -> FieldRule -> FieldRule+    updateNestedPresence key parent =+      parent {elementFields = move <$> parent ^. #elementFields}+      where+        move :: NestedRules -> NestedRules+        move rules =+          let (selected, remaining) = List.partition ((== key) . (^. #field)) (rules ^. #required)+           in rules {required = remaining, optional = selected <> rules ^. #optional}++    assertSingleDefinitionError matches = \case+      Left (definitionError :| []) | matches definitionError -> Right ()+      Left errors -> Left ("unexpected definition errors: " <> Text.pack (show (toList errors)))+      Right _ -> Left "expected profile definition to fail"++loadNestedReferenceSpec :: IO (Either Text ProfileSpec)+loadNestedReferenceSpec = do+  descriptorPath <- fixtureFilePath "profiles/nested-references-and-uniqueness.dhall"+  first ("failed to load nested reference profile: " <>) <$> loadProfileFile descriptorPath++nestedReferencePattern :: Text+nestedReferencePattern = "mori://[^/]+/[^/]+/okf/improvement-requests/concepts/IR-[1-9][0-9]*"++canonicalNestedReference :: Text+canonicalNestedReference = "mori://namespace/project/okf/improvement-requests/concepts/IR-9"++referenceConcept :: Text -> Text -> [Text] -> Either Text Concept+referenceConcept name rawReference criterionIds =+  profileConcept+    ("requests/" <> name)+    [ ("type", String "Improvement Request"),+      ("requestId", String "IR-1"),+      ("dependencies", toJSON [object ["ref" .= rawReference]]),+      ( "acceptanceCriteria",+        toJSON+          [ object ["id" .= criterionId, "text" .= ("Criterion " <> criterionId)]+          | criterionId <- criterionIds+          ]+      )+    ]+    "# Request\n"++nestedTestPathFor :: Text -> Int -> Text -> FieldPath+nestedTestPathFor parent elementIndex child =+  FieldPath (FieldName parent :| [ArrayIndex elementIndex, FieldName child])++testDocumentReferenceValidation :: Either Text ()+testDocumentReferenceValidation = do+  let referencePolicy = handleReferenceRule "ADR" ["mori", "MORI"] False+      selfPolicy = handleReferenceRule "ADR" [] True+      referenceRules =+        [ fieldRule "references" Nothing [] List Nothing Nothing (Just referencePolicy) Nothing,+          fieldRule "selfReference" Nothing [] Scalar Nothing Nothing (Just selfPolicy) Nothing+        ]+      spec :: ProfileSpec+      spec =+        testDocumentIdProfileSpec+          & #frontmatter+          .~ FrontmatterRules+            { membershipConstraints = [],+              uniqueValuesConstraints = [],+              presenceConstraints = [],+              timestampOrderConstraints = [],+              required = [requiredField "type", requiredField "title"],+              recommended = referenceRules,+              optional = []+            }+  compiled <- firstShow (compileProfile spec)+  duplicateA <- decisionConcept "decisions/duplicate-a" "Duplicate A" "ADR-3" []+  duplicateB <- decisionConcept "decisions/duplicate-b" "Duplicate B" "ADR-3" []+  source <-+    decisionConcept+      "decisions/source"+      "Source"+      "ADR-1"+      [ ( "references",+          toJSON+            [ String "ADR-2",+              String "ADR-99",+              String "PAT-3",+              String "not a reference",+              String "https://example.test/external",+              String "MORI://shinzui/okf/docs/one",+              String "ADR-1",+              Number 7,+              String "ADR-3"+            ]+        ),+        ("selfReference", String "ADR-1")+      ]+  target <- decisionConcept "decisions/target" "Target" "ADR-2" []+  duplicateAId <- parseTestConceptId "decisions/duplicate-a"+  duplicateBId <- parseTestConceptId "decisions/duplicate-b"+  sourceId <- parseTestConceptId "decisions/source"+  assertEqual+    [ DanglingHandleReference sourceId (indexedPath "references" 1) "ADR-99",+      ReferenceHandlePrefixMismatch sourceId (indexedPath "references" 2) "PAT-3" "ADR",+      MalformedDocumentReference sourceId (indexedPath "references" 3) (String "not a reference"),+      ExternalReferenceSchemeNotAllowed sourceId (indexedPath "references" 4) "https" ["mori"],+      SelfDocumentReference sourceId (indexedPath "references" 6) "ADR-1",+      MalformedDocumentReference sourceId (indexedPath "references" 7) (Number 7),+      DuplicateDocumentId "ADR-3" duplicateAId duplicateBId+    ]+    (validateProfile PermissiveConformance compiled [target, source, duplicateB, duplicateA])+  where+    decisionConcept cid title documentId extraFields =+      profileConcept+        cid+        ([("type", String "Decision Record"), ("title", String title), ("docId", String documentId)] <> extraFields)+        ("# " <> title <> "\n")+    indexedPath key elementIndex = FieldPath (FieldName key :| [ArrayIndex elementIndex])++-- | The whole point of the third presence list: absence is silent in both+-- validation modes, while a present value is checked exactly as hard as it would+-- be under @required@.+testOptionalFieldPresence :: Either Text ()+testOptionalFieldPresence = do+  let optionalRules =+        [ fieldRule "supersedes" Nothing ["ADR-1", "ADR-2"] Scalar Nothing Nothing Nothing Nothing,+          fieldRule "reviewedAt" Nothing [] Any (Just Rfc3339Utc) Nothing Nothing Nothing,+          fieldRule "tags" Nothing [] List Nothing Nothing Nothing Nothing+        ]+      spec =+        typeAwareProfileSpec+          { frontmatter =+              FrontmatterRules+                { membershipConstraints = [],+                  uniqueValuesConstraints = [],+                  presenceConstraints = [],+                  timestampOrderConstraints = [],+                  required = [requiredField "type"],+                  recommended = [requiredField "owner"],+                  optional = optionalRules+                },+            allowUnknownTypes = True,+            types = []+          }+  compiled <- firstShow (compileProfile spec)+  absent <- profileConcept "optional/absent" [("type", String "Extension"), ("owner", String "Ari")] "# Absent\n"+  -- A correctly shaped empty value counts as absent, so it is as silent as a key+  -- that was never written. (A blank value on a field that also declares a+  -- vocabulary or format still fails that check; presence and value are+  -- independent, which is exactly what this feature relies on.)+  emptied <-+    profileConcept+      "optional/emptied"+      [ ("type", String "Extension"),+        ("owner", String "Ari"),+        ("tags", toJSON ([] :: [Text]))+      ]+      "# Emptied\n"+  valid <-+    profileConcept+      "optional/valid"+      [ ("type", String "Extension"),+        ("owner", String "Ari"),+        ("supersedes", String "ADR-1"),+        ("reviewedAt", String "2026-07-30T00:00:00Z"),+        ("tags", toJSON (["profiles"] :: [Text]))+      ]+      "# Valid\n"+  invalid <-+    profileConcept+      "optional/invalid"+      [ ("type", String "Extension"),+        ("owner", String "Ari"),+        ("supersedes", String "ADR-9"),+        ("reviewedAt", String "2026-13-45T99:99:99Z"),+        ("tags", String "profiles")+      ]+      "# Invalid\n"+  invalidId <- parseTestConceptId "optional/invalid"+  for_ [PermissiveConformance, StrictAuthoring] $ \validationProfile -> do+    assertEqual [] (validateProfile validationProfile compiled [absent])+    assertEqual [] (validateProfile validationProfile compiled [emptied])+    assertEqual [] (validateProfile validationProfile compiled [valid])+    assertEqual+      [ ValueFormatMismatch invalidId (fieldPath "reviewedAt") Rfc3339Utc (String "2026-13-45T99:99:99Z"),+        ValueNotInVocabulary invalidId (fieldPath "supersedes") ["ADR-1", "ADR-2"] (String "ADR-9"),+        CardinalityMismatch invalidId (fieldPath "tags") List (String "profiles")+      ]+      (validateProfile validationProfile compiled [invalid])++-- | An optional field carrying a document-reference policy resolves handles the+-- same way a required one does; only the absence check differs.+testOptionalReferenceValidation :: Either Text ()+testOptionalReferenceValidation = do+  let spec :: ProfileSpec+      spec =+        testDocumentIdProfileSpec+          & #frontmatter+          .~ FrontmatterRules+            { membershipConstraints = [],+              uniqueValuesConstraints = [],+              presenceConstraints = [],+              timestampOrderConstraints = [],+              required = [requiredField "type", requiredField "title"],+              recommended = [],+              optional = [fieldRule "supersedes" Nothing [] Scalar Nothing Nothing (Just (handleReferenceRule "ADR" [] False)) Nothing]+            }+  compiled <- firstShow (compileProfile spec)+  target <- decisionTestConcept "decisions/target" "Target" "ADR-1" []+  silent <- decisionTestConcept "decisions/silent" "Silent" "ADR-2" []+  dangling <- decisionTestConcept "decisions/dangling" "Dangling" "ADR-3" [("supersedes", String "ADR-99")]+  danglingId <- parseTestConceptId "decisions/dangling"+  for_ [PermissiveConformance, StrictAuthoring] $ \validationProfile -> do+    assertEqual [] (validateProfile validationProfile compiled [target, silent])+    assertEqual+      [DanglingHandleReference danglingId (fieldPath "supersedes") "ADR-99"]+      (validateProfile validationProfile compiled [target, dangling])++-- | Optional members of a list-element record behave the same way inside every+-- record: never missing, always checked when present.+testOptionalNestedFieldPresence :: Either Text ()+testOptionalNestedFieldPresence = do+  let nestedRules =+        NestedRules+          { allowUnknownFields = True,+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [nestedFieldRule "kind" Nothing ["human", "model"] Scalar Nothing Nothing Nothing],+            recommended = [nestedFieldRule "notes" Nothing [] Scalar Nothing Nothing Nothing],+            optional = [nestedFieldRule "model" Nothing ["opus", "sonnet"] Scalar Nothing Nothing Nothing]+          }+  compiled <- firstShow (compileProfile (nestedProfileWithRules Any nestedRules Nothing))+  concept <-+    profileConcept+      "reviewed/optional"+      [ ("type", String "Reviewed Concept"),+        ( "reviews",+          toJSON+            [ object ["kind" .= ("human" :: Text), "notes" .= ("looks good" :: Text)],+              object ["kind" .= ("model" :: Text), "notes" .= ("ran it" :: Text), "model" .= ("opus" :: Text)],+              object ["kind" .= ("model" :: Text), "notes" .= ("ran it" :: Text), "model" .= ("gpt" :: Text)]+            ]+        )+      ]+      "# Optional\n"+  cid <- parseTestConceptId "reviewed/optional"+  for_ [PermissiveConformance, StrictAuthoring] $ \validationProfile ->+    assertEqual+      [ValueNotInVocabulary cid (nestedTestPath 2 "model") ["opus", "sonnet"] (String "gpt")]+      (validateProfile validationProfile compiled [concept])++-- | An optional key is declared for the purposes of field-name closure, so a+-- closed profile accepts it and still catches a misspelling of it.+testOptionalFieldClosure :: Either Text ()+testOptionalFieldClosure = do+  let closed =+        typeAwareProfileSpec+          { frontmatter =+              FrontmatterRules+                { membershipConstraints = [],+                  uniqueValuesConstraints = [],+                  presenceConstraints = [],+                  timestampOrderConstraints = [],+                  required = [requiredField "type"],+                  recommended = [],+                  optional = [requiredField "supersedes"]+                },+            allowUnknownTypes = True,+            allowUnknownFields = False,+            types = []+          }+  compiled <- firstShow (compileProfile closed)+  declared <- profileConcept "closed/declared" [("type", String "Extension"), ("supersedes", String "ADR-1")] "# Declared\n"+  typo <- profileConcept "closed/typo" [("type", String "Extension"), ("supersedse", String "ADR-1")] "# Typo\n"+  typoId <- parseTestConceptId "closed/typo"+  assertEqual [] (validateProfile PermissiveConformance compiled [declared])+  assertEqual+    [FieldNotInProfile typoId "supersedse"]+    (validateProfile PermissiveConformance compiled [typo])++-- | Declaring a key optional at one scope does not cancel the other scope's+-- presence clause. Merging accumulates clauses precisely so a type rule can+-- narrow but never silently weaken a profile-wide expectation.+testOptionalDoesNotCancelOtherScope :: Either Text ()+testOptionalDoesNotCancelOtherScope = do+  let ownerRule = requiredField "owner"+      specWith profileRules typeRules =+        typeAwareProfileSpec+          { frontmatter = profileRules,+            allowUnknownTypes = True,+            types = [withTypeFrontmatter typeRules (firstTypeRule typeAwareProfileSpec)]+          }+      recommendedThenOptional =+        specWith+          FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [requiredField "type"], recommended = [ownerRule], optional = []}+          FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [], recommended = [], optional = [ownerRule]}+      optionalThenRecommended =+        specWith+          FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [requiredField "type"], recommended = [], optional = [ownerRule]}+          FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [], recommended = [ownerRule], optional = []}+  concept <- profileConcept "owned/one" [("type", String "Owned Concept")] "# One\n"+  cid <- parseTestConceptId "owned/one"+  for_ [recommendedThenOptional, optionalThenRecommended] $ \spec -> do+    compiled <- firstShow (compileProfile spec)+    assertEqual [] (validateProfile PermissiveConformance compiled [concept])+    assertEqual+      [MissingRecommendedProfileField cid "owner" Nothing]+      (validateProfile StrictAuthoring compiled [concept])++-- | Compilation rejects the two contradictions the third list makes possible: a+-- key classified twice at one scope, and a condition on a rule that has no+-- presence check for it to gate.+testOptionalDefinitionErrors :: Either Text ()+testOptionalDefinitionErrors = do+  let key name = requiredField name+      specWith rules =+        typeAwareProfileSpec {frontmatter = rules, allowUnknownTypes = True, types = []}+      conditioned name sourceKey =+        fieldRule name Nothing [] Any Nothing Nothing Nothing (Just (FieldCondition sourceKey ["active"]))+      statusRule = fieldRule "status" Nothing ["active"] Scalar Nothing Nothing Nothing Nothing+  assertEqual+    (Left (ConflictingFieldRequirement Nothing "owner" :| []))+    (compileProfile (specWith FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [key "type", key "owner"], recommended = [], optional = [key "owner"]}))+  assertEqual+    (Left (ConflictingFieldRequirement Nothing "owner" :| []))+    (compileProfile (specWith FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [key "type"], recommended = [key "owner"], optional = [key "owner"]}))+  assertEqual+    (Left (DuplicateFieldRule Nothing "optional" "owner" :| []))+    (compileProfile (specWith FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [key "type"], recommended = [], optional = [key "owner", key "owner"]}))+  assertEqual+    (Left (OptionalFieldWithCondition Nothing (fieldPath "supersededBy") :| []))+    ( compileProfile+        (specWith FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [key "type", statusRule], recommended = [], optional = [conditioned "supersededBy" "status"]})+    )+  let nestedRules =+        NestedRules+          { allowUnknownFields = True,+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [nestedFieldRule "kind" Nothing ["model"] Scalar Nothing Nothing Nothing],+            recommended = [],+            optional = [nestedFieldRule "model" Nothing [] Scalar Nothing Nothing (Just (FieldCondition "kind" ["model"]))]+          }+  assertEqual+    (Left (OptionalFieldWithCondition Nothing (FieldPath (FieldName "reviews" :| [FieldName "model"])) :| []))+    (compileProfile (nestedProfileWithRules Any nestedRules Nothing))+  let optionalParent =+        specWith+          FrontmatterRules+            { membershipConstraints = [],+              uniqueValuesConstraints = [],+              presenceConstraints = [],+              timestampOrderConstraints = [],+              required = [key "type"],+              recommended = [],+              optional = [fieldRule "reviews" Nothing [] List Nothing (Just nestedRules) Nothing Nothing]+            }+  assertEqual+    (Left (OptionalFieldWithCondition Nothing (FieldPath (FieldName "reviews" :| [FieldName "model"])) :| []))+    (compileProfile optionalParent)++decisionTestConcept :: Text -> Text -> Text -> [(Text, Value)] -> Either Text Concept+decisionTestConcept cid title documentId extraFields =+  profileConcept+    cid+    ([("type", String "Decision Record"), ("title", String title), ("docId", String documentId)] <> extraFields)+    ("# " <> title <> "\n")++-- | The end-to-end proof, run against the fixture bundle a reader can also run+-- from the command line. Absence of the three optional keys is silent in both+-- modes; the one genuine recommendation still fails under strict authoring; the+-- conditional requirement in the same type still fires; and every optional key+-- that /is/ present is checked as hard as a required one.+testOptionalFieldsFixture :: IO (Either Text ())+testOptionalFieldsFixture = do+  descriptorPath <- fixtureFilePath "profiles/optional-fields.dhall"+  conditionPath <- fixtureFilePath "profiles/optional-conditional-invalid.dhall"+  collisionPath <- fixtureFilePath "profiles/optional-collision-invalid.dhall"+  loaded <- loadProfileFile descriptorPath+  conditionLoaded <- loadProfileFile conditionPath+  collisionLoaded <- loadProfileFile collisionPath+  root <- fixturePath "profile-optional-fields"+  concepts <- readBundle root+  pure $ do+    spec <- first ("failed to load optional-fields profile: " <>) loaded+    compiled <- firstShow (compileProfile spec)+    conditionSpec <- first ("failed to load invalid optional-condition profile: " <>) conditionLoaded+    collisionSpec <- first ("failed to load invalid optional-collision profile: " <>) collisionLoaded+    assertEqual+      ( Left+          ( OptionalFieldWithCondition (Just "Decision Record") (FieldPath (FieldName "reviews" :| [FieldName "model"]))+              :| [OptionalFieldWithCondition (Just "Decision Record") (fieldPath "supersededBy")]+          )+      )+      (compileProfile conditionSpec)+    assertEqual+      ( Left+          ( ConflictingFieldRequirement Nothing "reviewedBy"+              :| [ConflictingFieldRequirement (Just "Decision Record") "owner"]+          )+      )+      (compileProfile collisionSpec)+    accepted <- parseTestConceptId "decisions/accepted"+    badSupersedes <- parseTestConceptId "decisions/bad-supersedes"+    superseded <- parseTestConceptId "decisions/superseded"+    let valueViolations =+          [ ValueFormatMismatch badSupersedes (fieldPath "decidedAt") Rfc3339Utc (String "not a timestamp"),+            ValueNotInVocabulary badSupersedes (nestedReviewPath 0 "model") ["opus", "sonnet"] (String "gpt"),+            DanglingHandleReference badSupersedes (fieldPath "supersedes") "ADR-99",+            MissingProfileField superseded "supersededBy" (Just (FieldCondition "status" ["superseded"]))+          ]+    assertEqual valueViolations (validateProfile PermissiveConformance compiled concepts)+    assertEqual+      (MissingRecommendedProfileField accepted "reviewedBy" Nothing : valueViolations)+      (validateProfile StrictAuthoring compiled concepts)+  where+    nestedReviewPath elementIndex key =+      FieldPath (FieldName "reviews" :| [ArrayIndex elementIndex, FieldName key])++testClosedFieldValidation :: Either Text ()+testClosedFieldValidation = do+  let ownedRule :: TypeRule+      ownedRule =+        withTypeFrontmatter+          FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [requiredField "owner"], recommended = [], optional = []}+          (firstTypeRule typeAwareProfileSpec)+      reviewRule =+        withTypeName+          "Review"+          (withTypeFrontmatter FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [requiredField "reviewer"], recommended = [], optional = []} ownedRule)+      closed =+        typeAwareProfileSpec+          { frontmatter = FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [requiredField "type", requiredField "status"], recommended = [], optional = []},+            allowUnknownFields = False,+            idField = Just "requestId",+            requireBundleVersion = Nothing,+            types = [ownedRule, reviewRule]+          }+  compiled <- firstShow (compileProfile closed)+  typo <-+    profileConcept+      "owned/typo"+      [ ("type", String "Owned Concept"),+        ("title", String "Typo"),+        ("description", String "Core"),+        ("timestamp", String "2026-07-29T00:00:00Z"),+        ("resource", String "https://example.test/typo"),+        ("tags", toJSON (["profiles"] :: [Text])),+        ("requestId", String "IR-1"),+        ("owner", String "Ari"),+        ("reviewer", String "Bo"),+        ("stauts", String "draft")+      ]+      "# Typo\n"+  cid <- parseTestConceptId "owned/typo"+  assertEqual+    [ MissingProfileField cid "status" Nothing,+      FieldNotInProfile cid "reviewer",+      FieldNotInProfile cid "stauts"+    ]+    (validateProfile PermissiveConformance compiled [typo])+  let reopened = closed & #allowUnknownFields .~ True+  reopenedCompiled <- firstShow (compileProfile reopened)+  assertEqual+    [MissingProfileField cid "status" Nothing]+    (validateProfile PermissiveConformance reopenedCompiled [typo])++-- | The behavior this plan exists to deliver: a profile can require a+-- mapping-valued key and can demand a member of that mapping, reported at a path+-- such as @generated.by@.+testValidateObjectMember :: Either Text ()+testValidateObjectMember = do+  compiled <-+    firstShow+      (compileProfile (objectProfileWithRules "generated" Any (Just provenanceMemberRules) Nothing))+  cid <- parseTestConceptId "thing"+  -- A well-formed mapping satisfies the rule and reports nothing at all, which+  -- is the half of the fix that the old `missing profile-required field:+  -- generated` transcript got wrong.+  wellFormed <-+    profileConcept+      "thing"+      [ ("type", String "Thing"),+        ("generated", object ["by" .= ("human:nadeem" :: Text), "at" .= ("2026-06-18T00:00:00Z" :: Text)])+      ]+      "# Thing\n"+  assertEqual [] (validateProfile StrictAuthoring compiled [wellFormed])+  -- A mapping missing the demanded member reports that member, not the parent.+  missingMember <-+    profileConcept+      "thing"+      [ ("type", String "Thing"),+        ("generated", object ["at" .= ("2026-06-18T00:00:00Z" :: Text)])+      ]+      "# Thing\n"+  assertEqual+    [MissingNestedProfileField cid (objectMemberPath "generated" "by") Nothing]+    (validateProfile PermissiveConformance compiled [missingMember])+  -- Members are value-checked exactly as list-element members are, and the+  -- recommended member is reported only under strict authoring.+  badTimestamp <-+    profileConcept+      "thing"+      [("type", String "Thing"), ("generated", object ["by" .= ("human:nadeem" :: Text), "at" .= ("not-a-time" :: Text)])]+      "# Thing\n"+  assertEqual+    [ValueFormatMismatch cid (objectMemberPath "generated" "at") Rfc3339Utc (String "not-a-time")]+    (validateProfile PermissiveConformance compiled [badTimestamp])+  onlyBy <-+    profileConcept+      "thing"+      [("type", String "Thing"), ("generated", object ["by" .= ("human:nadeem" :: Text)])]+      "# Thing\n"+  assertEqual [] (validateProfile PermissiveConformance compiled [onlyBy])+  assertEqual+    [MissingRecommendedNestedProfileField cid (objectMemberPath "generated" "at") Nothing]+    (validateProfile StrictAuthoring compiled [onlyBy])+  -- The key itself is still demanded when it is absent entirely, and an empty+  -- mapping counts as absent for the same reason an empty list does.+  absent <- profileConcept "thing" [("type", String "Thing")] "# Thing\n"+  assertEqual+    [MissingProfileField cid "generated" Nothing]+    (validateProfile PermissiveConformance compiled [absent])+  emptyMapping <-+    profileConcept "thing" [("type", String "Thing"), ("generated", object [])] "# Thing\n"+  assertEqual+    [MissingProfileField cid "generated" Nothing]+    (validateProfile PermissiveConformance compiled [emptyMapping])++-- | OKF v0.2 specification §5.2 permits @verified@ as a list of mappings or as+-- one bare mapping and requires a consumer to treat the bare mapping as a+-- one-element list. A rule declaring both shapes checks them against the same+-- member rules, and neither spelling is a cardinality mismatch.+testValidateRecordOrList :: Either Text ()+testValidateRecordOrList = do+  compiled <-+    firstShow+      ( compileProfile+          (objectProfileWithRules "verified" Any (Just provenanceMemberRules) (Just provenanceMemberRules))+      )+  cid <- parseTestConceptId "thing"+  bareMapping <-+    profileConcept+      "thing"+      [("type", String "Thing"), ("verified", object ["at" .= ("2026-06-20T00:00:00Z" :: Text)])]+      "# Thing\n"+  assertEqual+    [MissingNestedProfileField cid (objectMemberPath "verified" "by") Nothing]+    (validateProfile PermissiveConformance compiled [bareMapping])+  oneElementList <-+    profileConcept+      "thing"+      [("type", String "Thing"), ("verified", toJSON [object ["at" .= ("2026-06-20T00:00:00Z" :: Text)]])]+      "# Thing\n"+  assertEqual+    [ MissingNestedProfileField+        cid+        (FieldPath (FieldName "verified" :| [ArrayIndex 0, FieldName "by"]))+        Nothing+    ]+    (validateProfile PermissiveConformance compiled [oneElementList])+  -- Both spellings are satisfiable, and neither reports a shape error.+  goodMapping <-+    profileConcept+      "thing"+      [("type", String "Thing"), ("verified", object ["by" .= ("human:nadeem" :: Text), "at" .= ("2026-06-20T00:00:00Z" :: Text)])]+      "# Thing\n"+  assertEqual [] (validateProfile StrictAuthoring compiled [goodMapping])++-- | A shape error does not cascade: a value of the wrong shape produces exactly+-- one 'CardinalityMismatch' naming the expected shape, and no member violations+-- from walking a record that is not there.+testValidateObjectWrongShape :: Either Text ()+testValidateObjectWrongShape = do+  compiled <-+    firstShow+      (compileProfile (objectProfileWithRules "generated" Any (Just provenanceMemberRules) Nothing))+  cid <- parseTestConceptId "thing"+  let listValue = toJSON [object ["by" .= ("human:nadeem" :: Text)]]+  concept <-+    profileConcept "thing" [("type", String "Thing"), ("generated", listValue)] "# Thing\n"+  assertEqual+    [CardinalityMismatch cid (fieldPath "generated") Object listValue]+    (validateProfile StrictAuthoring compiled [concept])++-- | Declaring no member rules at all still demands that the value be a mapping.+-- This is how an author says "this key must be an object" and nothing more,+-- which is the alternative to adding an @Object@ alternative to the published+-- Dhall union.+testValidateEmptyObjectRules :: Either Text ()+testValidateEmptyObjectRules = do+  compiled <-+    firstShow+      ( compileProfile+          ( objectProfileWithRules+              "generated"+              Any+              (Just (NestedRules {allowUnknownFields = True, presenceConstraints = [], timestampOrderConstraints = [], required = [], recommended = [], optional = []}))+              Nothing+          )+      )+  cid <- parseTestConceptId "thing"+  mapping <-+    profileConcept+      "thing"+      [("type", String "Thing"), ("generated", object ["anything" .= ("at all" :: Text)])]+      "# Thing\n"+  assertEqual [] (validateProfile StrictAuthoring compiled [mapping])+  scalarValue <-+    profileConcept "thing" [("type", String "Thing"), ("generated", String "nope")] "# Thing\n"+  assertEqual+    [CardinalityMismatch cid (fieldPath "generated") Object (String "nope")]+    (validateProfile PermissiveConformance compiled [scalarValue])++objectMemberPath :: Text -> Text -> FieldPath+objectMemberPath parent key = FieldPath (FieldName parent :| [FieldName key])++firstTypeRule :: ProfileSpec -> TypeRule+firstTypeRule spec =+  case spec ^. #types of+    rule : _ -> rule+    [] -> error "test profile unexpectedly has no type rules"++withTypeFrontmatter :: FrontmatterRules -> TypeRule -> TypeRule+withTypeFrontmatter+  replacement+  TypeRule+    { type_,+      description,+      guidance,+      pathPattern,+      resourceScheme,+      requireSchemaSection,+      schemaColumns,+      idPrefix+    } =+    TypeRule+      { type_,+        description,+        guidance,+        frontmatter = replacement,+        pathPattern,+        resourceScheme,+        requireSchemaSection,+        schemaColumns,+        idPrefix+      }++withTypeName :: Text -> TypeRule -> TypeRule+withTypeName+  replacement+  TypeRule+    { description,+      guidance,+      frontmatter,+      pathPattern,+      resourceScheme,+      requireSchemaSection,+      schemaColumns,+      idPrefix+    } =+    TypeRule+      { type_ = replacement,+        description,+        guidance,+        frontmatter,+        pathPattern,+        resourceScheme,+        requireSchemaSection,+        schemaColumns,+        idPrefix+      }++testProfileRulesApplyToUnknownTypes :: Either Text ()+testProfileRulesApplyToUnknownTypes = do+  compiled <- firstShow (compileProfile typeAwareProfileSpec)+  concept <- profileConcept "extensions/one" [("type", String "Extension Concept")] "# One\n"+  cid <- parseTestConceptId "extensions/one"+  assertEqual+    [MissingProfileField cid "title" Nothing]+    (validateProfile PermissiveConformance compiled [concept])++testStrictProfileRecommendations :: Either Text ()+testStrictProfileRecommendations = do+  compiled <- firstShow (compileProfile typeAwareProfileSpec)+  concept <-+    profileConcept+      "owned/one"+      [("type", String "Owned Concept"), ("title", String "One"), ("owner", String "Ari")]+      "# One\n"+  cid <- parseTestConceptId "owned/one"+  assertEqual [] (validateProfile PermissiveConformance compiled [concept])+  assertEqual+    [MissingRecommendedProfileField cid "reviewer" Nothing]+    (validateProfile StrictAuthoring compiled [concept])++-- | Build an in-memory concept from a raw ID, frontmatter pairs, and a body.+profileConcept :: Text -> [(Text, Value)] -> Text -> Either Text Concept+profileConcept rawId fieldPairs bodyText = do+  conceptId <- parseTestConceptId rawId+  pure (conceptFromDocument conceptId (OKFDocument (frontmatterFromFields fieldPairs) bodyText))++-- | A well-formed @# Schema@ section matching the profile's required columns.+schemaSectionBody :: Text+schemaSectionBody =+  Text.unlines+    [ "# Schema",+      "",+      "| Column | Type   | Nullable | Description |",+      "|--------|--------|----------|-------------|",+      "| id     | bigint | no       | Primary key |"+    ]++testProfileConformingTable :: Either Text ()+testProfileConformingTable = do+  concept <-+    profileConcept+      "schemas/sales/tables/orders"+      [ ("type", String "PostgreSQL Table"),+        ("title", String "Orders"),+        ("resource", String "postgresql://warehouse/sales/orders")+      ]+      schemaSectionBody+  assertEqual [] (validateTestProfile testProfileSpec [concept])++testProfileUnknownType :: Either Text ()+testProfileUnknownType = do+  concept <-+    profileConcept+      "schemas/sales/tables/bad"+      [("type", String "pg table"), ("resource", String "postgresql://x")]+      schemaSectionBody+  cid <- parseTestConceptId "schemas/sales/tables/bad"+  assertEqual+    [TypeNotInProfile cid "pg table", MissingProfileField cid "title" Nothing]+    (validateTestProfile testProfileSpec [concept])++testProfileMissingField :: Either Text ()+testProfileMissingField = do+  concept <-+    profileConcept+      "schemas/sales/tables/orders"+      [("type", String "PostgreSQL Table"), ("resource", String "postgresql://x")]+      schemaSectionBody+  cid <- parseTestConceptId "schemas/sales/tables/orders"+  assertEqual [MissingProfileField cid "title" Nothing] (validateTestProfile testProfileSpec [concept])++testProfileResourceMismatch :: Either Text ()+testProfileResourceMismatch = do+  concept <-+    profileConcept+      "schemas/sales/tables/orders"+      [("type", String "PostgreSQL Table"), ("title", String "Orders"), ("resource", String "mysql://x")]+      schemaSectionBody+  cid <- parseTestConceptId "schemas/sales/tables/orders"+  assertEqual+    [ResourceSchemeMismatch cid "postgresql" "mysql://x"]+    (validateTestProfile testProfileSpec [concept])++testProfilePathMismatch :: Either Text ()+testProfilePathMismatch = do+  concept <-+    profileConcept+      "tables/orders"+      [("type", String "PostgreSQL Table"), ("title", String "Orders"), ("resource", String "postgresql://x")]+      schemaSectionBody+  cid <- parseTestConceptId "tables/orders"+  assertEqual+    [PathPatternMismatch cid "PostgreSQL Table" "schemas/*/tables/*"]+    (validateTestProfile testProfileSpec [concept])++testProfileMissingSchema :: Either Text ()+testProfileMissingSchema = do+  concept <-+    profileConcept+      "schemas/sales/tables/orders"+      [("type", String "PostgreSQL Table"), ("title", String "Orders"), ("resource", String "postgresql://x")]+      "# Overview\n\nNo schema section here.\n"+  cid <- parseTestConceptId "schemas/sales/tables/orders"+  assertEqual+    [MissingSchemaSection cid "PostgreSQL Table"]+    (validateTestProfile testProfileSpec [concept])++testProfileSchemaColumnsMismatch :: Either Text ()+testProfileSchemaColumnsMismatch = do+  let mismatchBody =+        Text.unlines+          ["# Schema", "", "| Col | Type |", "|-----|------|", "| id  | bigint |"]+  concept <-+    profileConcept+      "schemas/sales/tables/orders"+      [("type", String "PostgreSQL Table"), ("title", String "Orders"), ("resource", String "postgresql://x")]+      mismatchBody+  cid <- parseTestConceptId "schemas/sales/tables/orders"+  assertEqual+    [SchemaColumnsMismatch cid "PostgreSQL Table" ["Column", "Type", "Nullable", "Description"] ["Col", "Type"]]+    (validateTestProfile testProfileSpec [concept])++testProfileConformingDocumentId :: Either Text ()+testProfileConformingDocumentId = do+  concept <-+    profileConcept+      "decisions/one"+      [("type", String "Decision Record"), ("title", String "One"), ("docId", String "ADR-1")]+      "# One\n"+  assertEqual [] (validateTestProfile testDocumentIdProfileSpec [concept])++testProfileMissingDocumentId :: Either Text ()+testProfileMissingDocumentId = do+  concept <-+    profileConcept+      "decisions/one"+      [("type", String "Decision Record"), ("title", String "One")]+      "# One\n"+  cid <- parseTestConceptId "decisions/one"+  assertEqual+    [MissingDocumentId cid "Decision Record" "ADR"]+    (validateTestProfile testDocumentIdProfileSpec [concept])++testProfileMalformedDocumentIds :: Either Text ()+testProfileMalformedDocumentIds = do+  leadingZero <-+    profileConcept+      "decisions/leading-zero"+      [("type", String "Decision Record"), ("title", String "Leading zero"), ("docId", String "ADR-007")]+      "# Leading zero\n"+  wrongPrefix <-+    profileConcept+      "decisions/wrong-prefix"+      [("type", String "Decision Record"), ("title", String "Wrong prefix"), ("docId", String "RFC-1")]+      "# Wrong prefix\n"+  leadingZeroId <- parseTestConceptId "decisions/leading-zero"+  wrongPrefixId <- parseTestConceptId "decisions/wrong-prefix"+  assertEqual+    [ MalformedDocumentId leadingZeroId "ADR" "ADR-007",+      MalformedDocumentId wrongPrefixId "ADR" "RFC-1"+    ]+    (validateTestProfile testDocumentIdProfileSpec [leadingZero, wrongPrefix])++testProfileDuplicateDocumentIds :: Either Text ()+testProfileDuplicateDocumentIds = do+  second <-+    profileConcept+      "decisions/second"+      [("type", String "Decision Record"), ("title", String "Second"), ("docId", String "ADR-1")]+      "# Second\n"+  firstConcept <-+    profileConcept+      "decisions/first"+      [("type", String "Decision Record"), ("title", String "First"), ("docId", String "ADR-1")]+      "# First\n"+  firstId <- parseTestConceptId "decisions/first"+  secondId <- parseTestConceptId "decisions/second"+  assertEqual+    [DuplicateDocumentId "ADR-1" firstId secondId]+    (validateTestProfile testDocumentIdProfileSpec [second, firstConcept])++testProfileDocumentIdsOffByDefault :: Either Text ()+testProfileDocumentIdsOffByDefault = do+  concept <-+    profileConcept+      "schemas/sales/tables/orders"+      [ ("type", String "PostgreSQL Table"),+        ("title", String "Orders"),+        ("resource", String "postgresql://warehouse/sales/orders"),+        ("docId", String "not-a-handle")+      ]+      schemaSectionBody+  assertEqual [] (validateTestProfile testProfileSpec [concept])++testSchemaSectionColumns :: Either Text ()+testSchemaSectionColumns =+  assertEqual+    (Just ["Column", "Type", "Nullable", "Description"])+    (schemaSectionColumns schemaSectionBody)++-- | Milestone 5: walking the deviating fixture and validating it against the+-- shipped descriptor produces exactly the expected advisory deviations.+testProfileDeviationsFixture :: IO (Either Text ())+testProfileDeviationsFixture = do+  descriptorPath <- fixtureFilePath "profiles/postgresql.dhall"+  loaded <- loadProfileFile descriptorPath+  root <- fixturePath "profile-deviations"+  concepts <- readBundle root+  pure $ case loaded of+    Left err -> Left ("failed to load profile: " <> err)+    Right spec -> do+      badId <- parseTestConceptId "schemas/sales/tables/bad"+      ordersId <- parseTestConceptId "schemas/sales/tables/orders"+      assertEqual+        [TypeNotInProfile badId "pg table", MissingProfileField ordersId "title" Nothing]+        (validateTestProfile spec concepts)++testDocumentIdDeviationsFixture :: IO (Either Text ())+testDocumentIdDeviationsFixture = do+  descriptorPath <- fixtureFilePath "profiles/decisions.dhall"+  loaded <- loadProfileFile descriptorPath+  root <- fixturePath "doc-id-deviations"+  concepts <- readBundle root+  pure $ case loaded of+    Left err -> Left ("failed to load document ID profile: " <> err)+    Right spec -> do+      firstId <- parseTestConceptId "decisions/first"+      secondId <- parseTestConceptId "decisions/second"+      thirdId <- parseTestConceptId "decisions/third"+      fourthId <- parseTestConceptId "decisions/fourth"+      assertEqual+        [ MissingDocumentId fourthId "Decision Record" "ADR",+          MalformedDocumentId thirdId "ADR" "ADR-007",+          DuplicateDocumentId "ADR-1" firstId secondId+        ]+        (validateTestProfile spec concepts)++testTypeAwareProfileFixture :: IO (Either Text ())+testTypeAwareProfileFixture = do+  descriptorPath <- fixtureFilePath "profiles/type-frontmatter.dhall"+  loaded <- loadProfileFile descriptorPath+  root <- fixturePath "profile-type-frontmatter"+  concepts <- readBundle root+  pure $ case loaded of+    Left err -> Left ("failed to load type-aware profile: " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      ownedId <- parseTestConceptId "owned"+      assertEqual [] (validateProfile PermissiveConformance compiled concepts)+      assertEqual+        [MissingRecommendedProfileField ownedId "reviewer" Nothing]+        (validateProfile StrictAuthoring compiled concepts)++-- | Declaration order is the author's; 'compiledProfileTypeNames' must not+-- reorder it, because generated documentation follows it.+testCompiledProfileTypeNames :: IO (Either Text ())+testCompiledProfileTypeNames = do+  descriptorPath <- fixtureFilePath "profiles/type-frontmatter.dhall"+  loaded <- loadProfileFile descriptorPath+  pure $ case loaded of+    Left err -> Left ("failed to load type-aware profile: " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      assertEqual ["Owned Concept", "Open Concept"] (compiledProfileTypeNames compiled)++-- | The merged view is what a reader of the profile actually needs: the type+-- rule names two keys, but four apply.+testCompiledProfileRulesMergeTypeScope :: IO (Either Text ())+testCompiledProfileRulesMergeTypeScope = do+  descriptorPath <- fixtureFilePath "profiles/type-frontmatter.dhall"+  loaded <- loadProfileFile descriptorPath+  pure $ case loaded of+    Left err -> Left ("failed to load type-aware profile: " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      let owned = compiledProfileRulesForType compiled "Owned Concept"+      assertEqual ["owner", "reviewer", "title", "type"] (Map.keys owned)+      ownerRule <- lookupCompiledRule "owner" owned+      assertEqual [(RequiredField, Nothing)] (presenceSummary ownerRule)+      reviewerRule <- lookupCompiledRule "reviewer" owned+      assertEqual [(RecommendedField, Nothing)] (presenceSummary reviewerRule)+      titleRule <- lookupCompiledRule "title" owned+      assertEqual (Just "Human-readable concept title.") (fieldRuleDescription titleRule)+      assertEqual ["title", "type"] (Map.keys (compiledProfileRulesForType compiled "Open Concept"))+      assertEqual+        (compiledProfileBaseRules compiled)+        (compiledProfileRulesForType compiled "Not In Profile")++-- | Pins the encoding an outside consumer is most likely to misread: @optional@+-- is an empty presence-clause list, not a constructor.+testCompiledProfileOptionalPresence :: IO (Either Text ())+testCompiledProfileOptionalPresence = do+  descriptorPath <- fixtureFilePath "profiles/optional-fields.dhall"+  loaded <- loadProfileFile descriptorPath+  pure $ case loaded of+    Left err -> Left ("failed to load optional-field profile: " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      let rules = compiledProfileRulesForType compiled "Decision Record"+      for_ ["supersedes", "decidedAt", "reviews", "originatingPlan"] $ \key -> do+        rule <- lookupCompiledRule key rules+        assertEqual [] (presenceSummary rule)+      statusRule <- lookupCompiledRule "status" rules+      assertEqual [(RequiredField, Nothing)] (presenceSummary statusRule)+      assertEqual ["accepted", "superseded"] (fieldRuleAllowedValues statusRule)+      assertEqual Scalar (fieldRuleCardinality statusRule)+      supersededByRule <- lookupCompiledRule "supersededBy" rules+      assertEqual+        [(RequiredField, Just (FieldCondition "status" ["superseded"]))]+        (presenceSummary supersededByRule)+      supersedesRule <- lookupCompiledRule "supersedes" rules+      assertEqual+        (Just (handleReferenceRule "ADR" [] False))+        (fieldRuleReference supersedesRule)+      reviewsRule <- lookupCompiledRule "reviews" rules+      nested <- maybe (Left "reviews declares no element fields") Right (fieldRuleElementFields reviewsRule)+      assertEqual ["kind", "model"] (Map.keys nested)+      kindRule <- lookupCompiledRule "kind" nested+      assertEqual [(RequiredField, Nothing)] (presenceSummary kindRule)+      assertEqual Nothing (fieldRuleElementFields kindRule)+      modelRule <- lookupCompiledRule "model" nested+      assertEqual [] (presenceSummary modelRule)++lookupCompiledRule :: Text -> Map Text EffectiveFieldRule -> Either Text EffectiveFieldRule+lookupCompiledRule key rules =+  maybe (Left ("no compiled rule for key " <> key)) Right (Map.lookup key rules)++-- | An 'EffectiveFieldRule' is abstract, so summarize its presence clauses+-- through the public accessors into something comparable.+presenceSummary :: EffectiveFieldRule -> [(FieldRequirement, Maybe FieldCondition)]+presenceSummary rule =+  [ (presenceClauseRequirement clause, presenceClauseCondition clause)+  | clause <- fieldRulePresenceClauses rule+  ]++-- * Profile documentation rendering++-- | Load a fixture profile, compile it, render documentation, and hand both the+-- compiled profile and the concepts to an assertion.+withRenderedProfileDocumentation ::+  FilePath ->+  DocumentationOptions ->+  (CompiledProfile -> [Concept] -> Either Text ()) ->+  IO (Either Text ())+withRenderedProfileDocumentation fixture options assertion = do+  descriptorPath <- fixtureFilePath fixture+  loaded <- loadProfileFile descriptorPath+  pure $ case loaded of+    Left err -> Left ("failed to load profile " <> Text.pack fixture <> ": " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      concepts <- firstShow (renderProfileDocumentation options compiled)+      assertion compiled concepts++conceptBodyLines :: Concept -> [Text]+conceptBodyLines concept = Text.lines (conceptDocument concept ^. #body)++-- | Assert on whole lines rather than substrings, so a failure names the line+-- that changed instead of pointing at an opaque haystack.+assertHasLine :: Text -> [Text] -> Either Text ()+assertHasLine expected bodyLines =+  assertBool+    ("expected body line " <> Text.pack (show expected))+    (expected `elem` bodyLines)++conceptAt :: Int -> [Concept] -> Either Text Concept+conceptAt offset concepts =+  case drop offset concepts of+    concept : _ -> Right concept+    [] -> Left ("no concept at position " <> Text.pack (show offset))++testProfileDocumentationSlug :: Either Text ()+testProfileDocumentationSlug = do+  assertEqual "bigquery-table" (profileDocumentationSlug "BigQuery Table")+  assertEqual "decision-record" (profileDocumentationSlug "Decision Record")+  assertEqual "c-header" (profileDocumentationSlug "C++ Header")+  assertEqual "spaced-out" (profileDocumentationSlug "  spaced  out  ")+  assertEqual "adr-7" (profileDocumentationSlug "ADR-7")+  assertEqual "" (profileDocumentationSlug "###")++-- | A profile with no rules at all beyond a required @type@, used to exercise+-- layout concerns without dragging in field rendering.+plainDocumentationTypeRule :: Text -> TypeRule+plainDocumentationTypeRule typeName =+  TypeRule+    { type_ = typeName,+      description = Nothing,+      guidance = Nothing,+      frontmatter = FrontmatterRules {membershipConstraints = [], uniqueValuesConstraints = [], presenceConstraints = [], timestampOrderConstraints = [], required = [], recommended = [], optional = []},+      pathPattern = Nothing,+      resourceScheme = Nothing,+      requireSchemaSection = False,+      schemaColumns = [],+      idPrefix = Nothing+    }++-- | Two distinct @type@ strings that slug identically, plus one that slugs to+-- nothing at all. No shipped descriptor has this shape, so the spec is built in+-- Haskell rather than by editing a fixture.+duplicateSlugProfileSpec :: ProfileSpec+duplicateSlugProfileSpec =+  ProfileSpec+    { name = "duplicate-slugs",+      description = Nothing,+      guidance = Nothing,+      okfVersion = "0.1",+      frontmatter =+        FrontmatterRules+          { membershipConstraints = [],+            uniqueValuesConstraints = [],+            presenceConstraints = [],+            timestampOrderConstraints = [],+            required = [fieldRule "type" Nothing [] Any Nothing Nothing Nothing Nothing],+            recommended = [],+            optional = []+          },+      allowUnknownTypes = False,+      allowUnknownFields = True,+      idField = Nothing,+      requireBundleVersion = Nothing,+      types =+        [ plainDocumentationTypeRule "Decision Record",+          plainDocumentationTypeRule "decision record",+          plainDocumentationTypeRule "###"+        ]+    }++testProfileDocumentationSlugCollisions :: Either Text ()+testProfileDocumentationSlugCollisions = do+  compiled <- firstShow (compileProfile duplicateSlugProfileSpec)+  concepts <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)+  assertEqual+    ["profile", "types/decision-record", "types/decision-record-2", "types/type-3"]+    (map (renderConceptId . conceptIdOf) concepts)++testProfileValueDisplayNames :: Either Text ()+testProfileValueDisplayNames = do+  assertEqual "any" (renderCardinalityName Any)+  assertEqual "scalar" (renderCardinalityName Scalar)+  assertEqual "list" (renderCardinalityName List)+  assertEqual "rfc3339-utc" (renderFieldFormatName Rfc3339Utc)+  assertEqual "date" (renderFieldFormatName Date)+  assertEqual "uri" (renderFieldFormatName Uri)+  assertEqual "uri-with-scheme(mori)" (renderFieldFormatName (UriWithScheme "mori"))+  assertEqual "document-handle(ADR)" (renderFieldFormatName (DocumentHandle "ADR"))++testProfileDocumentationRootConcept :: IO (Either Text ())+testProfileDocumentationRootConcept =+  withRenderedProfileDocumentation+    "profiles/optional-fields.dhall"+    defaultDocumentationOptions+    ( \compiled concepts -> do+        assertEqual (1 + length (compiledProfileTypeNames compiled)) (length concepts)+        root <- conceptAt 0 concepts+        assertEqual "profile" (renderConceptId (conceptIdOf root))+        assertEqual profileConceptType (conceptType root)+        assertEqual (Just "optional-fields") (conceptTitle root)+        let bodyLines = conceptBodyLines root+        assertHasLine "# optional-fields" bodyLines+        assertHasLine "- [Decision Record](/types/decision-record.md)" bodyLines+        assertHasLine "- Document ID field: `docId`" bodyLines+        assertHasLine "- Unknown concept types: rejected" bodyLines+        assertHasLine "- Unknown frontmatter keys: rejected" bodyLines+        -- Every profile-level setting has a bullet whether or not the profile+        -- sets it, so a reader learns the setting exists and that this profile+        -- leaves it alone. This fixture declares no bundle-version requirement.+        assertHasLine "- Required bundle version: none" bodyLines+    )++-- | A profile setting the renderer does not print is a silent hole in generated+-- documentation, so @requireBundleVersion@ is rendered in the same change that+-- adds it — the rule stated in+-- @docs\/adr\/11-growing-the-profile-descriptor-language.md@.+testProfileDocumentationRequiredBundleVersion :: Either Text ()+testProfileDocumentationRequiredBundleVersion = do+  compiled <- firstShow (compileProfile (requireBundleVersionProfile (Just "0.2")))+  concepts <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)+  root <- conceptAt 0 concepts+  assertHasLine "- Required bundle version: `0.2`" (conceptBodyLines root)++-- | A rule kind the renderer does not know about is a silent hole in generated+-- profile documentation, so object rules are rendered in the same change that+-- creates them. The bullet list is fixed by design, so a key that declares no+-- object shape says so explicitly rather than omitting the bullet.+testProfileDocumentationObjectFields :: Either Text ()+testProfileDocumentationObjectFields = do+  compiled <-+    firstShow+      (compileProfile (objectProfileWithRules "generated" Any (Just provenanceMemberRules) Nothing))+  concepts <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)+  root <- conceptAt 0 concepts+  let bodyLines = conceptBodyLines root+  assertHasLine "- Object fields:" bodyLines+  assertHasLine+    "    - `by` — required; allowed values: any; cardinality: any; format: none — Who or what produced this content."+    bodyLines+  assertHasLine+    "    - `at` — recommended; allowed values: any; cardinality: any; format: rfc3339-utc"+    bodyLines+  assertHasLine "- Element fields: none" bodyLines+  assertHasLine "- Cardinality: object" bodyLines+  -- A key with no object shape still carries the bullet, so the shape of the+  -- list never shifts between rules.+  assertHasLine "- Object fields: none" bodyLines++-- | Nested reference and parent uniqueness policies are compiled constraints,+-- so generated documentation must expose both rather than silently dropping+-- the rule kind that lives below the top-level field.+testProfileDocumentationNestedReferenceAndUniqueness :: IO (Either Text ())+testProfileDocumentationNestedReferenceAndUniqueness =+  withRenderedProfileDocumentation+    "profiles/nested-references-and-uniqueness.dhall"+    defaultDocumentationOptions+    ( \_compiled concepts -> do+        typeConcept <- conceptAt 1 concepts+        let bodyLines = conceptBodyLines typeConcept+        assertHasLine+          "    - `ref` — required; allowed values: any; cardinality: scalar; format: none; reference: local handles with prefix `IR`; external URIs with scheme `mori`; local handles prohibited; self-reference not allowed; external URI whole-value pattern `mori://[^/]+/[^/]+/okf/improvement-requests/concepts/IR-[1-9][0-9]*`"+          bodyLines+        assertHasLine "- Unique by: `id`" bodyLines+    )++testProfileDocumentationTypeConcept :: IO (Either Text ())+testProfileDocumentationTypeConcept =+  withRenderedProfileDocumentation+    "profiles/optional-fields.dhall"+    defaultDocumentationOptions+    ( \_compiled concepts -> do+        typeConcept <- conceptAt 1 concepts+        assertEqual "types/decision-record" (renderConceptId (conceptIdOf typeConcept))+        assertEqual profileTypeConceptType (conceptType typeConcept)+        assertEqual (Just "Decision Record") (conceptTitle typeConcept)+        let bodyLines = conceptBodyLines typeConcept+        assertHasLine "# Decision Record" bodyLines+        assertHasLine "Declared by the [optional-fields](/profile.md) profile." bodyLines+        assertHasLine "- Document ID prefix: `ADR`" bodyLines+        assertHasLine "- Path pattern: `decisions/*`" bodyLines+        assertHasLine "#### `status` — required" bodyLines+        assertHasLine "#### `supersededBy` — required when `status` is `superseded`" bodyLines+        assertHasLine "- Allowed values: `accepted`, `superseded`" bodyLines+        assertHasLine "#### `reviewedBy` — recommended" bodyLines+        assertHasLine "- Checked only under `--strict`" bodyLines+        assertHasLine "- Format: rfc3339-utc" bodyLines+        assertHasLine+          "    - `kind` — required; allowed values: `human`, `model`; cardinality: scalar; format: none"+          bodyLines+        assertHasLine+          "- Reference: local handles with prefix `ADR`; external URIs not allowed; local handles allowed; self-reference not allowed"+          bodyLines+        -- The profile-scope optional key must appear on the type page, under+        -- Optional: this is the merge being visible, which is the whole point.+        optionalHeading <- lineIndex "### Optional" bodyLines+        inheritedKey <- lineIndex "#### `originatingPlan` — optional" bodyLines+        assertBool+          "profile-scope optional key falls under the Optional heading"+          (optionalHeading < inheritedKey)+    )+  where+    lineIndex needle bodyLines =+      case List.elemIndex needle bodyLines of+        Just found -> Right found+        Nothing -> Left ("expected body line " <> Text.pack (show needle))++testProfileDocumentationInheritedRules :: IO (Either Text ())+testProfileDocumentationInheritedRules =+  withRenderedProfileDocumentation+    "profiles/type-frontmatter.dhall"+    defaultDocumentationOptions+    ( \_compiled concepts -> do+        assertEqual+          ["profile", "types/owned-concept", "types/open-concept"]+          (map (renderConceptId . conceptIdOf) concepts)+        owned <- conceptAt 1 concepts+        assertHasLine "#### `owner` — required" (conceptBodyLines owned)+        assertHasLine "#### `reviewer` — recommended" (conceptBodyLines owned)+        -- "Open Concept" declares no frontmatter of its own, so everything on+        -- its page is inherited from profile scope.+        open <- conceptAt 2 concepts+        let openBody = conceptBodyLines open+        assertEqual (Just "Open Concept") (conceptTitle open)+        assertHasLine "#### `title` — required" openBody+        assertHasLine "#### `type` — required" openBody+        assertHasLine "### Recommended" openBody+        assertHasLine "(none)" openBody+    )++-- | Root documentation carries profile guidance once, while type pages expose+-- the effective authoring procedure in profile-wide then type-specific order.+-- Blank values behave like absence, and guidance stays in Markdown body text+-- rather than leaking into generated frontmatter.+testProfileDocumentationGuidance :: IO (Either Text ())+testProfileDocumentationGuidance = do+  descriptorPath <- fixtureFilePath "profiles/guidance.dhall"+  loaded <- loadProfileFile descriptorPath+  pure $ do+    spec <- first ("failed to load guidance profile: " <>) loaded+    combined <- render spec+    combinedRoot <- conceptAt 0 combined+    combinedApi <- conceptAt 1 combined+    combinedFeature <- conceptAt 2 combined+    assertContains+      "root guidance follows description and precedes settings"+      ( "Authoring conventions for executable QA runbooks.\n\n"+          <> "## Guidance\n\n"+          <> profileProse+          <> "\n\n## Settings"+      )+      (conceptBody combinedRoot)+    assertContains+      "API guidance renders profile-wide before type-specific prose"+      ( "## Guidance\n\n"+          <> "### Profile-wide\n\n"+          <> profileProse+          <> "\n\n### Type-specific\n\n"+          <> apiProse+          <> "\n\n## Type settings"+      )+      (conceptBody combinedApi)+    assertContains+      "Feature guidance renders profile-wide before the event-stream procedure"+      ( "## Guidance\n\n"+          <> "### Profile-wide\n\n"+          <> profileProse+          <> "\n\n### Type-specific\n\n"+          <> featureProse+          <> "\n\n## Type settings"+      )+      (conceptBody combinedFeature)+    for_ combined $ \concept ->+      assertEqual+        Nothing+        (frontmatterLookup "guidance" (conceptDocument concept ^. #frontmatter))++    profileOnly <- render (spec & #types %~ map clearGuidance)+    profileOnlyApi <- conceptAt 1 profileOnly+    assertContains+      "profile-only type page labels its one effective scope"+      ("## Guidance\n\n### Profile-wide\n\n" <> profileProse <> "\n\n## Type settings")+      (conceptBody profileOnlyApi)+    assertOmits "profile-only type page omits the absent type scope" "### Type-specific" (conceptBody profileOnlyApi)++    typeOnly <- render (spec & #guidance .~ Nothing)+    typeOnlyRoot <- conceptAt 0 typeOnly+    typeOnlyApi <- conceptAt 1 typeOnly+    assertOmits "type-only profile page omits guidance" "## Guidance" (conceptBody typeOnlyRoot)+    assertContains+      "type-only type page labels its one effective scope"+      ("## Guidance\n\n### Type-specific\n\n" <> apiProse <> "\n\n## Type settings")+      (conceptBody typeOnlyApi)+    assertOmits "type-only type page omits the absent profile scope" "### Profile-wide" (conceptBody typeOnlyApi)++    blank <-+      render+        ( spec+            & #guidance+            .~ Just " \n\t\n"+            & #types+            %~ map (setGuidance (Just "\n  \n"))+        )+    for_ blank $ \concept ->+      assertOmits "blank guidance omits the section" "## Guidance" (conceptBody concept)++    absent <-+      render+        ( spec+            & #guidance+            .~ Nothing+            & #types+            %~ map clearGuidance+        )+    for_ absent $ \concept ->+      assertOmits "absent guidance omits the section" "## Guidance" (conceptBody concept)+  where+    profileProse =+      "Record the setup, cleanup, and evidence for every run.\n\nKeep supporting checks in source control and make the observed result reproducible."+    apiProse =+      "Add a source-controlled Hurl file that exercises the successful response and important failure responses.\n\nRun the Hurl file and retain the useful output as evidence."+    featureProse =+      "Exercise the public behavior, then inspect the generated domain-event stream.\n\nVerify event types, payloads, ordering, and stream identity, then verify the externally observable result."+    clearGuidance :: TypeRule -> TypeRule+    clearGuidance rule = rule & #guidance .~ Nothing+    setGuidance :: Maybe Text -> TypeRule -> TypeRule+    setGuidance value rule = rule & #guidance .~ value+    render spec = do+      compiled <- firstShow (compileProfile spec)+      firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)+    conceptBody concept = conceptDocument concept ^. #body+    assertContains label needle haystack =+      assertBool label (needle `Text.isInfixOf` haystack)+    assertOmits label needle haystack =+      assertBool label (not (needle `Text.isInfixOf` haystack))++testProfileDocumentationRoundTrip :: IO (Either Text ())+testProfileDocumentationRoundTrip =+  withRenderedProfileDocumentation+    "profiles/optional-fields.dhall"+    defaultDocumentationOptions+    ( \_compiled concepts ->+        for_ concepts $ \concept -> do+          reparsed <- firstShow (parseDocument (serializeConcept concept))+          assertEqual (conceptDocument concept) reparsed+    )++testProfileDocumentationValidates :: IO (Either Text ())+testProfileDocumentationValidates = do+  permissive <-+    withRenderedProfileDocumentation+      "profiles/optional-fields.dhall"+      defaultDocumentationOptions+      (\_compiled concepts -> assertEqual [] (validateInMemoryBundle PermissiveConformance VersionUndeclared concepts))+  -- The default options carry a @generated@ family, so strict validation of+  -- default output passes with no extra flag: that is the whole point of the+  -- default. The v0.1 @timestamp@ spelling still satisfies strict authoring too.+  strictResult <-+    withRenderedProfileDocumentation+      "profiles/optional-fields.dhall"+      defaultDocumentationOptions+      (\_compiled concepts -> assertEqual [] (validateInMemoryBundle StrictAuthoring VersionUndeclared concepts))+  strictLegacyResult <-+    withRenderedProfileDocumentation+      "profiles/optional-fields.dhall"+      defaultDocumentationOptions {generated = Nothing, timestamp = Just "2026-07-31T00:00:00Z"}+      (\_compiled concepts -> assertEqual [] (validateInMemoryBundle StrictAuthoring VersionUndeclared concepts))+  pure (permissive >> strictResult >> strictLegacyResult)++-- | Re-parse the serialized document, so the assertion proves the family+-- survives serialization rather than merely living in the in-memory value.+reparsedGenerated :: Concept -> Either Text (Maybe Generated)+reparsedGenerated concept = do+  reparsed <- firstShow (parseDocument (serializeConcept concept))+  pure (readGenerated (reparsed ^. #frontmatter))++testProfileDocumentationDefaultGenerated :: IO (Either Text ())+testProfileDocumentationDefaultGenerated =+  withRenderedProfileDocumentation+    "profiles/optional-fields.dhall"+    defaultDocumentationOptions+    ( \_compiled concepts -> for_ concepts $ \concept -> do+        assertEqual+          (Just (Generated (ProcessActor "okf-profile-document") Nothing))+          (conceptGenerated concept)+        roundTripped <- reparsedGenerated concept+        assertEqual+          (Just (Generated (ProcessActor "okf-profile-document") Nothing))+          roundTripped+    )++testProfileDocumentationExplicitGenerated :: IO (Either Text ())+testProfileDocumentationExplicitGenerated =+  withRenderedProfileDocumentation+    "profiles/optional-fields.dhall"+    defaultDocumentationOptions+      { generated = Just (Generated (HumanActor "nadeem") (Just "2026-08-01T00:00:00Z"))+      }+    ( \_compiled concepts -> for_ concepts $ \concept -> do+        roundTripped <- reparsedGenerated concept+        assertEqual+          (Just (Generated (HumanActor "nadeem") (Just "2026-08-01T00:00:00Z")))+          roundTripped+    )++-- | The escape hatch: a caller who wants no provenance at all gets none.+testProfileDocumentationOmittedGenerated :: IO (Either Text ())+testProfileDocumentationOmittedGenerated =+  withRenderedProfileDocumentation+    "profiles/optional-fields.dhall"+    defaultDocumentationOptions {generated = Nothing}+    ( \_compiled concepts -> for_ concepts $ \concept -> do+        assertEqual Nothing (conceptGenerated concept)+        roundTripped <- reparsedGenerated concept+        assertEqual Nothing roundTripped+    )++testProfileDocumentationLinksResolve :: IO (Either Text ())+testProfileDocumentationLinksResolve =+  withRenderedProfileDocumentation+    "profiles/optional-fields.dhall"+    defaultDocumentationOptions+    ( \_compiled concepts -> do+        assertEqual [] (danglingReferences concepts)+        rootId <- parseTestConceptId "profile"+        typeId <- parseTestConceptId "types/decision-record"+        let graphEdges = buildGraph concepts ^. #edges+        assertBool+          "profile links to the type document"+          (Edge rootId typeId `elem` graphEdges)+        assertBool+          "the type document links back to the profile"+          (Edge typeId rootId `elem` graphEdges)+    )++testProfileDocumentationByteStable :: IO (Either Text ())+testProfileDocumentationByteStable = do+  descriptorPath <- fixtureFilePath "profiles/optional-fields.dhall"+  loaded <- loadProfileFile descriptorPath+  pure $ case loaded of+    Left err -> Left ("failed to load optional-field profile: " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      firstRender <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)+      secondRender <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)+      assertEqual firstRender secondRender+      -- Compare the serialized text too: serializeDocument sorts frontmatter+      -- keys, so a Concept-only comparison would miss a nondeterministic+      -- serialization.+      assertEqual (map serializeConcept firstRender) (map serializeConcept secondRender)++-- | The generated bundle must survive the round trip the next plan's @--write@+-- mode performs: write it out, generate indexes over it, walk it back.+testProfileDocumentationFilesystemRoundTrip :: IO (Either Text ())+testProfileDocumentationFilesystemRoundTrip = do+  descriptorPath <- fixtureFilePath "profiles/optional-fields.dhall"+  loaded <- loadProfileFile descriptorPath+  case loaded >>= (firstShow . compileProfile) of+    Left err -> pure (Left ("failed to prepare optional-field profile: " <> err))+    Right compiled ->+      case renderProfileDocumentation defaultDocumentationOptions compiled of+        Left err -> pure (Left ("render failed: " <> Text.pack (show err)))+        Right concepts -> do+          temporaryDirectory <- getTemporaryDirectory+          root <- createTempDirectory temporaryDirectory "okf-profile-documentation"+          writeBundle root concepts+          indexResult <- writeBundleIndexes root+          walked <- walkBundle root+          removeDirectoryRecursive root+          pure $ do+            _ <- firstShow indexResult+            walkedConcepts <- firstShow walked+            assertEqual+              (List.sort (map (renderConceptId . conceptIdOf) concepts))+              (List.sort (map (renderConceptId . conceptIdOf) walkedConcepts))++testClosedFieldsFixture :: IO (Either Text ())+testClosedFieldsFixture = do+  descriptorPath <- fixtureFilePath "profiles/closed-fields.dhall"+  loaded <- loadProfileFile descriptorPath+  root <- fixturePath "profile-closed-fields"+  concepts <- readBundle root+  pure $ case loaded of+    Left err -> Left ("failed to load closed-field profile: " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      typoId <- parseTestConceptId "requests/typo"+      assertEqual+        [MissingProfileField typoId "status" Nothing, FieldNotInProfile typoId "stauts"]+        (validateProfile PermissiveConformance compiled concepts)++testCardinalityFixture :: IO (Either Text ())+testCardinalityFixture = do+  descriptorPath <- fixtureFilePath "profiles/cardinality.dhall"+  loaded <- loadProfileFile descriptorPath+  root <- fixturePath "profile-cardinality"+  concepts <- readBundle root+  pure $ case loaded of+    Left err -> Left ("failed to load cardinality profile: " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      badId <- parseTestConceptId "bad"+      assertEqual+        [ CardinalityMismatch badId (fieldPath "tags") List (String "one"),+          CardinalityMismatch badId (fieldPath "title") Scalar (toJSON (["One", "Two"] :: [Text]))+        ]+        (validateProfile PermissiveConformance compiled concepts)++testFormatsFixture :: IO (Either Text ())+testFormatsFixture = do+  descriptorPath <- fixtureFilePath "profiles/formats.dhall"+  loaded <- loadProfileFile descriptorPath+  root <- fixturePath "profile-formats"+  concepts <- readBundle root+  pure $ case loaded of+    Left err -> Left ("failed to load format profile: " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      badId <- parseTestConceptId "bad"+      assertEqual+        [ ValueFormatMismatch badId (fieldPath "docId") (DocumentHandle "ADR") (String "ADR-007"),+          ValueFormatMismatch badId (fieldPath "homepage") (UriWithScheme "https") (String "mailto:owner@example.test"),+          ValueFormatMismatch badId (fieldPath "links") Uri (toJSON (["https://example.test/good", "https://example.test/bad%ZZ"] :: [Text])),+          ValueFormatMismatch badId (fieldPath "published") Date (String "2026-13-45"),+          ValueFormatMismatch badId (fieldPath "timestamp") Rfc3339Utc (String "2026-07-29T17:00:00+01:00")+        ]+        (validateProfile PermissiveConformance compiled concepts)++testNestedReviewsFixture :: IO (Either Text ())+testNestedReviewsFixture = do+  descriptorPath <- fixtureFilePath "profiles/nested-reviews.dhall"+  loaded <- loadProfileFile descriptorPath+  root <- fixturePath "profile-nested-reviews"+  concepts <- readBundle root+  pure $ case loaded of+    Left err -> Left ("failed to load nested review profile: " <> err)+    Right spec -> do+      compiled <- firstShow (compileProfile spec)+      badId <- parseTestConceptId "bad"+      let permissiveExpected =+            [ NestedElementNotRecord badId (FieldPath (FieldName "reviews" :| [ArrayIndex 1])) (String "not-a-record"),+              CardinalityMismatch badId (nestedTestPath 2 "context") Scalar (toJSON (["wrong"] :: [Text])),+              MissingNestedProfileField badId (nestedTestPath 2 "outcome") Nothing,+              ValueFormatMismatch badId (nestedTestPath 2 "reviewed_at") Rfc3339Utc (String "2026-13-45T99:99:99Z"),+              ValueNotInVocabulary badId (nestedTestPath 2 "scope") reviewScopes (String "invalid")+            ]+      assertEqual permissiveExpected (validateProfile PermissiveConformance compiled concepts)+      assertEqual+        [ NestedElementNotRecord badId (FieldPath (FieldName "reviews" :| [ArrayIndex 1])) (String "not-a-record"),+          CardinalityMismatch badId (nestedTestPath 2 "context") Scalar (toJSON (["wrong"] :: [Text])),+          MissingRecommendedNestedProfileField badId (nestedTestPath 2 "notes") Nothing,+          MissingNestedProfileField badId (nestedTestPath 2 "outcome") Nothing,+          ValueFormatMismatch badId (nestedTestPath 2 "reviewed_at") Rfc3339Utc (String "2026-13-45T99:99:99Z"),+          ValueNotInVocabulary badId (nestedTestPath 2 "scope") reviewScopes (String "invalid")+        ]+        (validateProfile StrictAuthoring compiled concepts)++testConditionalFieldsFixture :: IO (Either Text ())+testConditionalFieldsFixture = do+  descriptorPath <- fixtureFilePath "profiles/conditional-fields.dhall"+  invalidDescriptorPath <- fixtureFilePath "profiles/conditional-fields-invalid.dhall"+  loaded <- loadProfileFile descriptorPath+  invalidLoaded <- loadProfileFile invalidDescriptorPath+  root <- fixturePath "profile-conditions"+  concepts <- readBundle root+  pure $ do+    spec <- first ("failed to load conditional profile: " <>) loaded+    compiled <- firstShow (compileProfile spec)+    invalidSpec <- first ("failed to load invalid conditional profile: " <>) invalidLoaded+    decisionsMissingStatus <- parseTestConceptId "decisions/missing-status"+    decisionsSuperseded <- parseTestConceptId "decisions/superseded"+    postgresqlOperational <- parseTestConceptId "postgresql/operational"+    postgresqlProjection <- parseTestConceptId "postgresql/projection"+    reviewsMixed <- parseTestConceptId "reviews/mixed"+    assertEqual+      ( Left+          ( ConditionFieldHasUnreachableValues+              Nothing+              (fieldPath "supersededBy")+              (fieldPath "status")+              ["superseded"]+              ["active"]+              :| []+          )+      )+      (compileProfile invalidSpec)+    assertEqual+      [ MissingProfileField decisionsMissingStatus "status" Nothing,+        MissingProfileField decisionsSuperseded "supersededBy" (Just (FieldCondition "status" ["superseded"])),+        MissingProfileField postgresqlProjection "sourceQuery" (Just (FieldCondition "derivationKind" ["projection"])),+        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "effort") (Just (FieldCondition "kind" ["model"])),+        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "model") (Just (FieldCondition "kind" ["model"])),+        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "provider") (Just (FieldCondition "kind" ["model"]))+      ]+      (validateProfile PermissiveConformance compiled concepts)+    assertEqual+      [ MissingProfileField decisionsMissingStatus "status" Nothing,+        MissingProfileField decisionsSuperseded "supersededBy" (Just (FieldCondition "status" ["superseded"])),+        MissingRecommendedProfileField postgresqlOperational "runbook" (Just (FieldCondition "derivationKind" ["operational"])),+        MissingProfileField postgresqlProjection "sourceQuery" (Just (FieldCondition "derivationKind" ["projection"])),+        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "effort") (Just (FieldCondition "kind" ["model"])),+        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "model") (Just (FieldCondition "kind" ["model"])),+        MissingNestedProfileField reviewsMixed (nestedReviewPath 0 "provider") (Just (FieldCondition "kind" ["model"]))+      ]+      (validateProfile StrictAuthoring compiled concepts)+  where+    nestedReviewPath elementIndex key =+      FieldPath (FieldName "reviews" :| [ArrayIndex elementIndex, FieldName key])++testDocumentReferencesFixture :: IO (Either Text ())+testDocumentReferencesFixture = do+  descriptorPath <- fixtureFilePath "profiles/document-references.dhall"+  invalidDescriptorPath <- fixtureFilePath "profiles/document-references-invalid.dhall"+  loaded <- loadProfileFile descriptorPath+  invalidLoaded <- loadProfileFile invalidDescriptorPath+  root <- fixturePath "profile-document-references"+  concepts <- readBundle root+  pure $ do+    spec <- first ("failed to load document-reference profile: " <>) loaded+    compiled <- firstShow (compileProfile spec)+    invalidSpec <- first ("failed to load invalid document-reference profile: " <>) invalidLoaded+    case compileProfile invalidSpec of+      Left _ -> Right ()+      Right _ -> Left "expected invalid document-reference descriptor to fail compilation"+    duplicateAId <- parseTestConceptId "decisions/duplicate-a"+    duplicateBId <- parseTestConceptId "decisions/duplicate-b"+    sourceId <- parseTestConceptId "decisions/source"+    assertEqual+      [ DanglingHandleReference sourceId (indexedPath 1) "ADR-99",+        ReferenceHandlePrefixMismatch sourceId (indexedPath 2) "PAT-3" "ADR",+        MalformedDocumentReference sourceId (indexedPath 3) (String "not a reference"),+        ExternalReferenceSchemeNotAllowed sourceId (indexedPath 4) "https" ["mori"],+        SelfDocumentReference sourceId (indexedPath 6) "ADR-1",+        MalformedDocumentReference sourceId (indexedPath 7) (Number 7),+        DuplicateDocumentId "ADR-3" duplicateAId duplicateBId+      ]+      (validateProfile PermissiveConformance compiled concepts)+  where+    indexedPath elementIndex = FieldPath (FieldName "references" :| [ArrayIndex elementIndex])++validateTestProfile :: ProfileSpec -> [Concept] -> [ProfileViolation]+validateTestProfile spec concepts =+  case compileProfile spec of+    Left errors -> error ("test profile failed to compile: " <> show errors)+    Right compiled -> validateProfile PermissiveConformance compiled concepts++substringIndex :: Text -> Text -> Maybe Int+substringIndex needle haystack =+  let (prefix, match) = Text.breakOn needle haystack+   in if Text.null match then Nothing else Just (Text.length prefix)++strictlyIncreasing :: [Int] -> Bool+strictlyIncreasing xs = and (zipWith (<) xs (drop 1 xs))++sampleDocument :: Text+sampleDocument =+  Text.unlines+    [ "---",+      "type: BigQuery Table",+      "title: Users",+      "description: User records.",+      "timestamp: 2026-06-16T00:00:00Z",+      "tags: [users]",+      "---",+      "",+      "# Schema",+      "",+      "Body text."+    ]++-- | Natural order: digit runs by value, then by spelling length, everything+-- else by code point, and only identical texts equal.+testCompareNatural :: Either Text ()+testCompareNatural = do+  let ordered smaller larger = do+        assertEqual (smaller, larger, LT) (smaller, larger, compareNatural smaller larger)+        assertEqual (larger, smaller, GT) (larger, smaller, compareNatural larger smaller)+  ordered "IR-2" "IR-10"+  ordered "IR-9" "IR-10"+  ordered "IR-2" "IR-02"+  ordered "v0.9" "v0.13"+  ordered "a" "b"+  ordered "B" "a"+  ordered "2026-08-08" "2026-10-01"+  ordered "IR-10" "IR-10a"+  ordered "7" "x"+  assertEqual EQ (compareNatural "IR-10" "IR-10")+  assertEqual EQ (compareNatural "" "")++-- | @--sort@ arguments: a selector, an optional @:asc@ or @:desc@, and errors+-- for anything else after a colon.+testParseSortKey :: Either Text ()+testParseSortKey = do+  let status = TopLevelField "status"+  assertEqual (Right (SortKey status Ascending)) (parseSortKey "status")+  assertEqual (Right (SortKey status Ascending)) (parseSortKey "status:asc")+  assertEqual (Right (SortKey status Descending)) (parseSortKey "status:desc")+  assertEqual+    (Right (SortKey (NestedField "reviews" "outcome") Descending))+    (parseSortKey "reviews.outcome:desc")+  assertEqual (Left (InvalidSortDirection "status:up" "up")) (parseSortKey "status:up")+  assertEqual (Left (InvalidSortDirection "status:DESC" "DESC")) (parseSortKey "status:DESC")+  assertEqual (Left (InvalidSortDirection "a:b:c" "c")) (parseSortKey "a:b:c")+  assertEqual (Left (SortKeySelectorError EmptyFilterKey)) (parseSortKey ":desc")+  assertEqual (Left (SortKeySelectorError EmptyFilterKey)) (parseSortKey "")+  assertEqual (Left (SortKeySelectorError (FilterKeyTooDeep "a.b.c"))) (parseSortKey "a.b.c")+  assertEqual+    "sort direction must be asc or desc, not up, in status:up"+    (either renderSortKeyParseError (const "") (parseSortKey "status:up"))+  for_ ["status", "status:desc", "reviews.outcome", "generated.by:desc"] $ \raw ->+    assertEqual (Right raw) (renderSortKey <$> parseSortKey raw)+  assertEqual (Right "status") (renderSortKey <$> parseSortKey "status:asc")++-- | 'sortConcepts' over the concept-sorting fixture, whose concept-ID order+-- (a-ten, b-two, c-nine, d-none, e-one) matches none of the orders asked for.+testSortConceptsOverFixture :: IO (Either Text ())+testSortConceptsOverFixture = do+  root <- fixturePath "concept-sorting"+  concepts <- readBundle root+  pure $ do+    let key name = SortKey (TopLevelField name)+        sortedBy keys = Text.drop (Text.length "requests/") . renderConceptId . conceptIdOf <$> sortConcepts keys concepts++    assertEqual ["a-ten", "b-two", "c-nine", "d-none", "e-one"] (sortedBy [])+    -- Natural order puts IR-10 after IR-9; the concept with no ID is last.+    assertEqual ["e-one", "b-two", "c-nine", "a-ten", "d-none"] (sortedBy [key "requestId" Ascending])+    -- Descending reverses the present values only: absence stays last.+    assertEqual ["a-ten", "c-nine", "b-two", "e-one", "d-none"] (sortedBy [key "requestId" Descending])+    -- Numbers compare numerically, and the 2-2 tie keeps concept-ID order.+    assertEqual ["c-nine", "a-ten", "e-one", "b-two", "d-none"] (sortedBy [key "priority" Ascending])+    -- A second key breaks the tie instead.+    assertEqual+      ["b-two", "e-one", "a-ten", "c-nine", "d-none"]+      (sortedBy [key "priority" Descending, key "requestId" Ascending])+    -- A list sorts by its smallest element ascending and largest descending.+    assertEqual ["a-ten", "d-none", "b-two", "c-nine", "e-one"] (sortedBy [key "tags" Ascending])+    assertEqual ["a-ten", "b-two", "d-none", "c-nine", "e-one"] (sortedBy [key "tags" Descending])+    -- A key no concept carries leaves the order alone.+    assertEqual ["a-ten", "b-two", "c-nine", "d-none", "e-one"] (sortedBy [key "nothing" Descending])+    -- Titles Nine, None, One, Ten, Two in code-point order.+    assertEqual ["c-nine", "d-none", "e-one", "a-ten", "b-two"] (sortedBy [key "title" Ascending])++assertEqual :: (Eq value, Show value) => value -> value -> Either Text ()+assertEqual expected actual+  | expected == actual = Right ()+  | otherwise =+      Left+        ( "expected "+            <> Text.pack (show expected)+            <> ", got "+            <> Text.pack (show actual)+        )++assertBool :: Text -> Bool -> Either Text ()+assertBool _ True = Right ()+assertBool label False = Left label++firstShow :: (Show err) => Either err value -> Either Text value+firstShow =+  either (Left . Text.pack . show) Right++readBundle :: FilePath -> IO [Concept]+readBundle root = do+  result <- walkBundle root+  case result of+    Left bundleError -> fail (show bundleError)+    Right concepts -> pure concepts++-- | Every file the bundle holds, for the path-valued frontmatter check.+readBundleInventory :: FilePath -> IO BundleInventory+readBundleInventory root = do+  result <- walkBundleInventory root+  case result of+    Left bundleError -> fail (show bundleError)+    Right inventory -> pure inventory++-- | 'validateBundle' over a bundle assembled in memory, whose inventory is+-- exactly the concepts' own source paths. Used wherever a test builds concepts+-- rather than walking a directory; a test that does have a root passes+-- 'readBundleInventory' instead, so the non-Markdown files are seen.+validateInMemoryBundle :: ValidationProfile -> VersionDeclaration -> [Concept] -> [BundleValidationError]+validateInMemoryBundle profile declaration concepts =+  validateBundle profile declaration (bundleInventoryOfConcepts concepts) concepts++-- | The filter grammar @okf concepts@ hands to 'parseFieldEquals': one @=@, and+-- a key that is either top-level or one level deep.+testParseConceptFilters :: Either Text ()+testParseConceptFilters = do+  assertEqual+    (Right (FieldEquals (TopLevelField "status") "accepted"))+    (parseFieldEquals "status=accepted")+  assertEqual+    (Right (FieldEquals (NestedField "reviews" "outcome") "approved"))+    (parseFieldEquals "reviews.outcome=approved")+  -- Split on the first '=' only, so a value carrying its own survives intact.+  assertEqual+    (Right (FieldEquals (TopLevelField "resource") "postgres://host/db?a=b"))+    (parseFieldEquals "resource=postgres://host/db?a=b")+  -- The value is verbatim: whitespace in a shell argument was typed on purpose.+  assertEqual+    (Right (FieldEquals (TopLevelField "title") " "))+    (parseFieldEquals "title= ")+  assertEqual (Left (MissingFilterSeparator "status")) (parseFieldEquals "status")+  assertEqual (Left (FilterKeyTooDeep "a.b.c")) (parseFieldSelector "a.b.c")+  assertEqual (Left EmptyFilterKey) (parseFieldSelector ".x")+  assertEqual (Left EmptyFilterKey) (parseFieldSelector "reviews.")+  assertEqual (Left EmptyFilterKey) (parseFieldSelector "")+  -- Rendering is the inverse a diagnostic quotes back.+  assertEqual "status=accepted" (renderFilter (FieldEquals (TopLevelField "status") "accepted"))+  assertEqual "reviews.outcome" (renderFieldSelector (NestedField "reviews" "outcome"))+  assertEqual "completedAt" (renderFilter (FieldPresent (TopLevelField "completedAt")))+  assertEqual "!status" (renderFilter (FieldAbsent (TopLevelField "status")))++-- | The @--where@ grammar: legacy @KEY=VALUE@ untouched, standalone @!=@ and+-- set conditions, and parenthesized expressions with JSON strings.+testParseWhereConditions :: Either Text ()+testParseWhereConditions = do+  let status = TopLevelField "status"+      outcome = NestedField "reviews" "outcome"+      parsed = parseWhereCondition+      predicate = Right . PredicateWhere+      equals selector value = PredicateAtom (FieldEquals selector value)+      syntaxOffset = \case+        Left (InvalidWhereSyntax _ offset _) -> Just offset+        _ -> Nothing+      isSyntaxError result = isJust (syntaxOffset result)+      assertOffset expected raw =+        first (\message -> raw <> ": " <> message) (assertEqual (Just expected) (syntaxOffset (parsed raw)))++  -- Legacy arguments keep their exact meaning, however expression-like the+  -- value looks.+  assertEqual (Right (LegacyWhere (FieldEquals status "accepted"))) (parsed "status=accepted")+  assertEqual+    (Right (LegacyWhere (FieldEquals (TopLevelField "resource") "postgres://host/db?a=b")))+    (parsed "resource=postgres://host/db?a=b")+  assertEqual (Right (LegacyWhere (FieldEquals (TopLevelField "title") " "))) (parsed "title= ")+  assertEqual (Right (LegacyWhere (FieldEquals (TopLevelField "title") ""))) (parsed "title=")+  assertEqual+    (Right (LegacyWhere (FieldEquals (TopLevelField "title") "research and development")))+    (parsed "title=research and development")+  assertEqual+    (Right (LegacyWhere (FieldEquals (TopLevelField "title") "a in [\"b\"]")))+    (parsed "title=a in [\"b\"]")+  -- Quotes outside expression mode are part of the literal value.+  assertEqual (Right (LegacyWhere (FieldEquals status "\"accepted\""))) (parsed "status=\"accepted\"")+  -- A key that merely starts like a keyword is still a legacy key.+  assertEqual (Right (LegacyWhere (FieldEquals (TopLevelField "status index") "1"))) (parsed "status index=1")+  assertEqual (Left (LegacyWhereParseError (MissingFilterSeparator "status"))) (parsed "status")+  assertEqual (Left (LegacyWhereParseError (FilterKeyTooDeep "a.b.c"))) (parsed "a.b.c=x")++  -- Standalone inequality: the value is verbatim, like a legacy equality's.+  assertEqual (predicate (PredicateNotEquals status "completed")) (parsed "status!=completed")+  assertEqual (predicate (PredicateNotEquals status "")) (parsed "status!=")+  assertEqual (predicate (PredicateNotEquals status " a=b ")) (parsed "status!= a=b ")+  assertEqual (predicate (PredicateNotEquals outcome "approved")) (parsed "reviews.outcome!=approved")++  -- Standalone sets are JSON, consume the whole argument, and keep the first+  -- occurrence of a duplicate.+  assertEqual+    (predicate (PredicateIn status ("accepted" :| ["proposed"])))+    (parsed "status in [\"accepted\",\"proposed\"]")+  assertEqual+    (predicate (PredicateNotIn status ("completed" :| ["rejected"])))+    (parsed "status not in [ \"completed\" , \"rejected\" ]  ")+  assertEqual+    (predicate (PredicateIn status ("a" :| ["b"])))+    (parsed "status in [\"a\",\"b\",\"a\"]")+  assertEqual (predicate (PredicateIn status ("a" :| []))) (parsed "status in[\"a\"]")+  assertEqual+    (predicate (PredicateNotIn outcome ("changes-requested" :| [])))+    (parsed "reviews.outcome not in [\"changes-requested\"]")+  -- A recognized prefix commits: a malformed set is an error, never an+  -- equality.+  assertOffset 11 "status in []"+  assertOffset 10 "status in "+  assertOffset 11 "status in [1]"+  assertOffset 21 "status in [\"accepted\""+  assertOffset 23 "status in [\"accepted\"] x"+  assertOffset 11 "status in [\"bad\\q\"]"+  assertOffset 14 "status not in accepted"++  -- Expressions.+  assertEqual (predicate (equals status "accepted")) (parsed "(status=\"accepted\")")+  assertEqual (predicate (equals status "accepted")) (parsed "  ( status = \"accepted\" )  ")+  assertEqual (predicate (PredicateNotEquals status "completed")) (parsed "(status!=\"completed\")")+  assertEqual+    (predicate (PredicateAtom (FieldPresent (TopLevelField "completedAt"))))+    (parsed "(has(completedAt))")+  assertEqual (predicate (PredicateAtom (FieldAbsent status))) (parsed "(missing( status ))")+  assertEqual+    ( predicate+        ( PredicateAnd+            (PredicateIn status ("accepted" :| ["proposed"]))+            (PredicateNot (equals (TopLevelField "tags") "archived"))+        )+    )+    (parsed "(status in [\"accepted\",\"proposed\"] and not (tags=\"archived\"))")+  -- not binds tighter than and, which binds tighter than or; both group left.+  let a = equals (TopLevelField "a") "1"+      b = equals (TopLevelField "b") "2"+      c = equals (TopLevelField "c") "3"+  assertEqual+    (predicate (PredicateOr a (PredicateAnd b c)))+    (parsed "(a=\"1\" or b=\"2\" and c=\"3\")")+  assertEqual+    (predicate (PredicateAnd (PredicateOr a b) c))+    (parsed "((a=\"1\" or b=\"2\") and c=\"3\")")+  assertEqual+    (predicate (PredicateAnd (PredicateNot a) b))+    (parsed "(not a=\"1\" and b=\"2\")")+  assertEqual+    (predicate (PredicateOr (PredicateOr a b) c))+    (parsed "(a=\"1\" or b=\"2\" or c=\"3\")")+  assertEqual+    (predicate (PredicateNot (PredicateNot a)))+    (parsed "(not not a=\"1\")")+  -- Whitespace includes tabs and newlines.+  assertEqual (predicate (PredicateAnd a b)) (parsed "(a=\"1\"\n\tand\tb=\"2\")")+  -- Keywords need a word boundary: 'orphan' and 'notes' are keys.+  assertEqual+    (predicate (PredicateOr a (equals (TopLevelField "orphan") "x")))+    (parsed "(a=\"1\" or orphan=\"x\")")+  assertEqual (predicate (equals (TopLevelField "notes") "x")) (parsed "(notes=\"x\")")+  assertEqual (predicate (equals (TopLevelField "not") "x")) (parsed "(not=\"x\")")+  assertEqual+    (predicate (equals (TopLevelField "has") "x"))+    (parsed "(has=\"x\")")+  -- Strings decode JSON escapes, Unicode included, and are never coerced.+  assertEqual+    (predicate (equals (TopLevelField "title") "say \"hi\"\\ é ✓"))+    (parsed "(title=\"say \\\"hi\\\"\\\\ \\u00e9 ✓\")")+  assertEqual (predicate (equals (TopLevelField "title") "")) (parsed "(title=\"\")")+  assertEqual (predicate (equals (TopLevelField "usage_count") "12")) (parsed "(usage_count=\"12\")")+  assertEqual+    (predicate (PredicateIn outcome ("approved" :| [])))+    (parsed "(reviews.outcome in [\"approved\"])")++  -- Rejections, each at the offset where reading stopped. An invalid+  -- parenthesized argument never falls back to a literal equality.+  assertOffset 22 "(status=\"accepted\" and)"+  assertOffset 8 "(status=accepted)"+  assertOffset 18 "(status=\"accepted\""+  assertOffset 8 "(status=\"accepted)"+  assertOffset 20 "(status=\"accepted\") and (a=\"1\")"+  assertOffset 8 "(status ~ \"x\")"+  assertOffset 1 "()"+  assertOffset 4 "(a.b.c=\"x\")"+  assertOffset 12 "(status in [])"+  assertOffset 12 "(status in [true])"+  assertOffset 8 "(status=\"\\x\")"+  assertOffset 12 "(status not [\"a\"])"+  assertOffset 5 "(has status)"+  assertBool "uppercase AND is not an operator" (isSyntaxError (parsed "(a=\"1\" AND b=\"2\")"))+  assertBool+    "a syntax error names what was expected"+    ( case parsed "(status=\"accepted\" and)" of+        Left parseError -> "expected a condition" `Text.isPrefixOf` renderWhereParseError parseError+        Right _ -> False+    )+  assertEqual+    "expected at least one string in the set; an empty set can never match at offset 11\n  status in []\n             ^"+    (either renderWhereParseError (const "") (parsed "status in []"))++  -- Rendering reads back as the same condition.+  for_+    [ "status=accepted",+      "title=research and development",+      "status!=completed",+      "status in [\"accepted\",\"proposed\"]",+      "status not in [\"completed\",\"rejected\"]",+      "(status=\"accepted\")",+      "(missing(status) or status!=\"completed\")",+      "(status in [\"accepted\",\"proposed\"] and not (tags=\"archived\"))",+      "(a=\"1\" or (b=\"2\" or c=\"3\"))",+      "((a=\"1\" or b=\"2\") and c=\"3\")",+      "(not has(x) and not not y=\"\\\"q\\\"\")",+      "(title=\"say \\\"hi\\\" é\")"+    ]+    $ \raw -> do+      condition <- first renderWhereParseError (parsed raw)+      assertEqual (Right condition) (parsed (renderWhereCondition condition))+  assertEqual "status!=completed" (either (const "") renderWhereCondition (parsed "status!=completed"))+  assertEqual+    "(status in [\"accepted\",\"proposed\"] and not (tags=\"archived\"))"+    (either (const "") renderWhereCondition (parsed "(status in [\"accepted\",\"proposed\"] and not (tags=\"archived\"))"))++-- | A filter compares against text, so every non-textual scalar needs a+-- spelling. Aeson writes an integral number without a trailing @.0@, which is+-- what makes @--where usage_count=12@ match a YAML @usage_count: 12@.+testQueryScalarText :: Either Text ()+testQueryScalarText = do+  assertEqual (Just "accepted") (scalarText (String "accepted"))+  assertEqual (Just "12") (scalarText (Number 12))+  assertEqual (Just "0.5") (scalarText (Number 0.5))+  assertEqual (Just "true") (scalarText (Bool True))+  assertEqual Nothing (scalarText Null)+  assertEqual Nothing (scalarText (toJSON (["a", "b"] :: [Text])))+  assertEqual Nothing (scalarText (object ["by" .= ("human:nadeem" :: Text)]))++-- | 'filterConcepts' over the concept-filter fixture bundle, which is built so+-- that every matching shape appears exactly once: a key present on some+-- concepts and absent on another, a list-valued key with more elements than the+-- filter names, a nested key inside a list of records whose elements disagree,+-- and a nested key inside a plain record.+testFilterConceptsOverFixture :: IO (Either Text ())+testFilterConceptsOverFixture = do+  root <- fixturePath "concept-filters"+  concepts <- readBundle root+  pure $ do+    let selected filters = renderConceptId . conceptIdOf <$> filterConcepts filters concepts+    assertEqual+      ["notes/scratch", "requests/alpha", "requests/beta", "requests/gamma"]+      (selected [])+    assertEqual ["requests/alpha"] (selected [FieldEquals (TopLevelField "status") "accepted"])+    -- Existential over a list: alpha is tagged [profiles, cli] and still matches.+    assertEqual+      ["requests/alpha", "requests/beta"]+      (selected [FieldEquals (TopLevelField "tags") "cli"])+    -- Existential over list elements: gamma's first review is changes-requested.+    assertEqual+      ["requests/alpha", "requests/gamma"]+      (selected [FieldEquals (NestedField "reviews" "outcome") "approved"])+    -- The other nested shape: a record-valued key rather than a list of records.+    assertEqual+      ["notes/scratch", "requests/beta"]+      (selected [FieldEquals (NestedField "generated" "by") "human:nadeem"])+    assertEqual ["notes/scratch"] (selected [FieldAbsent (TopLevelField "status")])+    assertEqual ["requests/gamma"] (selected [FieldPresent (TopLevelField "completedAt")])+    -- A key no concept carries selects nothing, which is not an error.+    assertEqual [] (selected [FieldEquals (TopLevelField "status") "withdrawn"])+    -- Repeating a key is an "or".+    assertEqual+      ["requests/alpha", "requests/beta"]+      ( selected+          [ FieldEquals (TopLevelField "status") "accepted",+            FieldEquals (TopLevelField "status") "proposed"+          ]+      )+    -- Different keys are an "and".+    assertEqual+      ["requests/beta"]+      ( selected+          [ FieldEquals (TopLevelField "type") "Improvement Request",+            FieldEquals (TopLevelField "status") "proposed"+          ]+      )+    -- Grouping is by question as well as key, so these two are a conjunction of+    -- two groups and can never both hold.+    assertEqual+      []+      ( selected+          [ FieldEquals (TopLevelField "status") "accepted",+            FieldAbsent (TopLevelField "status")+          ]+      )++-- | A profile checks the /question/, not the bundle: a filter naming a key the+-- profile does not declare, or a value outside a closed vocabulary, can never+-- select anything, and saying so is the whole reason @okf concepts@ takes a+-- @--profile@.+testCheckFiltersAgainstProfile :: IO (Either Text ())+testCheckFiltersAgainstProfile = do+  descriptorPath <- fixtureFilePath "profiles/concept-filters.dhall"+  loaded <- loadProfileFile descriptorPath+  pure $ do+    spec <- first ("failed to load concept-filter profile: " <>) loaded+    compiled <- firstShow (compileProfile spec)+    openTypes <- firstShow (compileProfile (spec & #allowUnknownTypes .~ True))+    let checkAll = checkFiltersAgainstProfile compiled []+        checkFor wantedTypes = checkFiltersAgainstProfile compiled wantedTypes+        statusVocabulary = ["proposed", "accepted", "completed", "rejected"]+        reviewOutcomes = ["approved", "changes-requested", "commented"]+        typeNames = ["Improvement Request", "Note"]++    -- THE REGRESSION GUARD FOR THE ORDERING TRAP. 'status' is both an OKF v0.2+    -- core key ('coreFrontmatterFields' holds it) and a key this profile closes+    -- with four values. A refactor that asks "is this a core key?" before "does+    -- the profile declare it?" passes every other assertion in this test and+    -- silently waves the headline typo straight through.+    assertEqual+      [FilterValueNotInVocabulary (TopLevelField "status") "acepted" statusVocabulary]+      (checkAll [FieldEquals (TopLevelField "status") "acepted"])+    assertEqual [] (checkAll [FieldEquals (TopLevelField "status") "accepted"])++    -- A key no scope declares, whatever question is asked of it.+    assertEqual+      [FilterFieldNotDeclared (TopLevelField "statuz")]+      (checkAll [FieldEquals (TopLevelField "statuz") "x"])+    assertEqual+      [FilterFieldNotDeclared (TopLevelField "statuz")]+      (checkAll [FieldPresent (TopLevelField "statuz")])+    assertEqual+      [FilterFieldNotDeclared (TopLevelField "statuz")]+      (checkAll [FieldAbsent (TopLevelField "statuz")])+    assertEqual [] (checkAll [FieldPresent (TopLevelField "completedAt")])++    -- A nested member's vocabulary is reached through the parent's+    -- elementFields; a member declared without one accepts anything.+    assertEqual+      [FilterValueNotInVocabulary (NestedField "reviews" "outcome") "approvd" reviewOutcomes]+      (checkAll [FieldEquals (NestedField "reviews" "outcome") "approvd"])+    assertEqual [] (checkAll [FieldEquals (NestedField "reviews" "reviewer") "anyone"])+    assertEqual+      [FilterFieldNotDeclared (NestedField "reviews" "reviewr")]+      (checkAll [FieldEquals (NestedField "reviews" "reviewr") "anyone"])+    -- The other nested shape: objectFields on a record-valued key.+    assertEqual [] (checkAll [FieldEquals (NestedField "generated" "by") "human:nadeem"])++    -- The core-field fallback, for a key the profile never mentions: 'timestamp'+    -- is an OKF key, and okf owns the shape of 'verified' as well as its name.+    assertEqual [] (checkAll [FieldEquals (TopLevelField "timestamp") "2026-08-09T00:00:00Z"])+    assertEqual [] (checkAll [FieldEquals (NestedField "verified" "by") "human:nadeem"])++    -- 'type' has no allowedValues anywhere; its vocabulary is the profile's+    -- declared type names, and only while allowUnknownTypes is False.+    assertEqual+      [FilterValueNotInVocabulary (TopLevelField "type") "Ghost" typeNames]+      (checkAll [FieldEquals (TopLevelField "type") "Ghost"])+    assertEqual [] (checkAll [FieldEquals (TopLevelField "type") "Note"])+    assertEqual+      []+      (checkFiltersAgainstProfile openTypes [] [FieldEquals (TopLevelField "type") "Ghost"])++    -- THE REGRESSION GUARD FOR THE SCOPE TRAP. 'noteKind' is declared plainly+    -- profile-wide and closed on 'Note' alone. Treating the profile-wide rules+    -- as a scope of their own would see an empty allowed-value list there, read+    -- it as "unconstrained", and never report anything for this key at all.+    -- Asking about 'Note' specifically must report; asking about every type must+    -- not, because an 'Improvement Request' really may hold any value here.+    assertEqual+      [FilterValueNotInVocabulary (TopLevelField "noteKind") "bogus" ["scratch", "reference"]]+      (checkFor ["Note"] [FieldEquals (TopLevelField "noteKind") "bogus"])+    assertEqual [] (checkFor ["Note"] [FieldEquals (TopLevelField "noteKind") "scratch"])+    assertEqual [] (checkAll [FieldEquals (TopLevelField "noteKind") "bogus"])++    -- Restricting to the types the command line named is a real restriction:+    -- 'targetPlan' is declared only on 'Improvement Request'.+    assertEqual [] (checkAll [FieldPresent (TopLevelField "targetPlan")])+    assertEqual [] (checkFor ["Improvement Request"] [FieldPresent (TopLevelField "targetPlan")])+    assertEqual+      [FilterFieldNotDeclared (TopLevelField "targetPlan")]+      (checkFor ["Note"] [FieldPresent (TopLevelField "targetPlan")])++    -- Every error is reported, not only the first.+    assertEqual+      [ FilterValueNotInVocabulary (TopLevelField "status") "acepted" statusVocabulary,+        FilterFieldNotDeclared (TopLevelField "statuz")+      ]+      ( checkAll+          [ FieldEquals (TopLevelField "status") "acepted",+            FieldEquals (TopLevelField "statuz") "x"+          ]+      )++-- | 'filterConceptsWhere' over the concept-filter fixture: inclusion,+-- exclusion, explicit composition, and how they meet legacy grouping.+testFilterConceptsWhereOverFixture :: IO (Either Text ())+testFilterConceptsWhereOverFixture = do+  root <- fixturePath "concept-filters"+  concepts <- readBundle root+  pure $ do+    let status = TopLevelField "status"+        tags = TopLevelField "tags"+        outcome = NestedField "reviews" "outcome"+        equals selector value = PredicateAtom (FieldEquals selector value)+        selectedWith legacy conditions =+          renderConceptId . conceptIdOf <$> filterConceptsWhere legacy conditions concepts+        selected = selectedWith []+        predicates = map PredicateWhere+        parsedConditions raws = traverse (first renderWhereParseError . parseWhereCondition) raws+        selectedParsed raws = selected <$> parsedConditions raws++    assertEqual+      ["requests/alpha", "requests/beta"]+      (selected (predicates [PredicateIn status ("accepted" :| ["proposed"])]))+    -- Scratch has no status and Gamma is completed.+    assertEqual+      ["requests/alpha", "requests/beta"]+      (selected (predicates [PredicateNotIn status ("completed" :| ["rejected"])]))+    -- Repeated explicit conditions are a conjunction, even on one key.+    assertEqual+      ["requests/alpha", "requests/beta"]+      (selected (predicates [PredicateNotEquals status "completed", PredicateNotEquals status "rejected"]))+    assertEqual+      ["requests/beta"]+      ( selected+          ( predicates+              [ PredicateIn status ("accepted" :| ["proposed"]),+                PredicateIn status ("proposed" :| ["completed"])+              ]+          )+      )+    assertEqual [] (selected (predicates [PredicateAnd (equals status "accepted") (equals status "proposed")]))+    -- A negative value question is universal over a list: Alpha's other tag+    -- does not save it, nor does Gamma's approving review.+    assertEqual [] (selected (predicates [PredicateNotEquals tags "cli"]))+    assertEqual ["requests/beta"] (selected (predicates [PredicateNotEquals tags "profiles"]))+    assertEqual+      ["requests/alpha"]+      (selected (predicates [PredicateNotIn outcome ("changes-requested" :| [])]))+    -- Boolean not negates its whole operand, absence included.+    assertEqual+      ["notes/scratch", "requests/alpha", "requests/beta"]+      (selected (predicates [PredicateNot (equals status "completed")]))+    assertEqual+      ["notes/scratch", "requests/beta"]+      (selected (predicates [PredicateNot (PredicateAtom (FieldPresent (TopLevelField "reviews")))]))+    assertEqual+      ["requests/gamma"]+      (selected (predicates [PredicateAtom (FieldPresent (TopLevelField "completedAt"))]))+    -- Absence is spelled out when it should be included.+    assertEqual+      ["notes/scratch", "requests/alpha"]+      (selected (predicates [PredicateOr (equals status "accepted") (PredicateAtom (FieldAbsent status))]))+    -- A disjunction across keys.+    assertEqual+      ["requests/alpha", "requests/gamma"]+      (selected (predicates [PredicateOr (equals status "completed") (equals tags "profiles")]))+    assertEqual+      ["requests/alpha", "requests/beta"]+      (selected (predicates [PredicateAnd (PredicateIn status ("accepted" :| ["proposed"])) (equals tags "cli")]))++    -- Legacy repetition stays an "or", and a predicate then narrows it.+    assertEqual+      ["requests/alpha", "requests/beta"]+      (selected [LegacyWhere (FieldEquals status "accepted"), LegacyWhere (FieldEquals status "proposed")])+    assertEqual+      ["requests/alpha"]+      ( selected+          [ LegacyWhere (FieldEquals status "accepted"),+            LegacyWhere (FieldEquals status "proposed"),+            PredicateWhere (PredicateNotEquals status "proposed")+          ]+      )+    -- A supplied --type filter and a legacy type= still share one group.+    assertEqual+      ["notes/scratch", "requests/alpha", "requests/beta", "requests/gamma"]+      ( selectedWith+          [FieldEquals (TopLevelField "type") "Note"]+          [LegacyWhere (FieldEquals (TopLevelField "type") "Improvement Request")]+      )+    -- Stored frontmatter only: no default status is invented for Scratch.+    assertEqual [] (selected [LegacyWhere (FieldEquals status "stable")])+    assertEqual [] (selected (predicates [PredicateIn status ("stable" :| [])]))++    -- The same selections, read from the strings a user types.+    assertEqual+      (Right ["requests/alpha", "requests/beta"])+      (selectedParsed ["status not in [\"completed\",\"rejected\"]"])+    assertEqual (Right ["requests/alpha"]) (selectedParsed ["reviews.outcome not in [\"changes-requested\"]"])+    assertEqual+      (Right ["notes/scratch", "requests/alpha", "requests/beta"])+      (selectedParsed ["(not (status=\"completed\"))"])+    assertEqual+      (Right ["notes/scratch", "requests/alpha", "requests/beta"])+      (selectedParsed ["(missing(status) or status!=\"completed\")"])++-- | Value predicates over the shapes the fixture does not hold: null, empty+-- lists, records, lists of records, non-textual scalars, escaped strings, and+-- lists mixing scalars with records.+testMatchesPredicateEdgeCases :: Either Text ()+testMatchesPredicateEdgeCases = do+  let key = TopLevelField+      conceptWith rawId pairs = profileConcept rawId pairs ""+      matches predicate concept = matchesPredicate predicate concept+  nullStatus <- conceptWith "edge/null" [("status", Null)]+  emptyList <- conceptWith "edge/empty" [("status", toJSON ([] :: [Text]))]+  record <- conceptWith "edge/record" [("status", object ["a" .= (1 :: Int)])]+  records <- conceptWith "edge/records" [("status", toJSON [object ["a" .= (1 :: Int)]])]+  emptyText <- conceptWith "edge/empty-text" [("status", String "")]+  scalars <- conceptWith "edge/scalars" [("flag", Bool True), ("count", Number 12), ("title", String "say \"hi\"")]+  mixed <- conceptWith "edge/mixed" [("tags", toJSON [String "cli", object ["a" .= (1 :: Int)]])]++  -- No comparable scalar: every direct value question fails, positive or+  -- negative, while presence still sees the key and boolean not inverts.+  for_ [nullStatus, emptyList, record, records] $ \concept -> do+    assertBool "!= needs a comparable scalar" (not (matches (PredicateNotEquals (key "status") "x") concept))+    assertBool "not in needs a comparable scalar" (not (matches (PredicateNotIn (key "status") ("x" :| [])) concept))+    assertBool "in needs a comparable scalar" (not (matches (PredicateIn (key "status") ("x" :| [])) concept))+    assertBool "not inverts a failed equality" (matches (PredicateNot (PredicateAtom (FieldEquals (key "status") "x"))) concept)+  assertBool "a stored null is present" (matches (PredicateAtom (FieldPresent (key "status"))) nullStatus)+  assertBool "an empty list is absent" (matches (PredicateAtom (FieldAbsent (key "status"))) emptyList)+  assertBool "a record is present" (matches (PredicateAtom (FieldPresent (key "status"))) record)++  -- An empty string is a comparable string.+  assertBool "empty string != x" (matches (PredicateNotEquals (key "status") "x") emptyText)+  assertBool "empty string in [\"\"]" (matches (PredicateIn (key "status") ("" :| [])) emptyText)+  assertBool "empty string != \"\" fails" (not (matches (PredicateNotEquals (key "status") "") emptyText))++  -- Numbers and booleans compare as their JSON text.+  assertBool "true in [true]" (matches (PredicateIn (key "flag") ("true" :| [])) scalars)+  assertBool "true != false" (matches (PredicateNotEquals (key "flag") "false") scalars)+  assertBool "12 not in [12]" (not (matches (PredicateNotIn (key "count") ("12" :| [])) scalars))+  assertBool "12 != 13" (matches (PredicateNotEquals (key "count") "13") scalars)+  -- An escaped expression string reaches the stored text.+  quoted <- first renderWhereParseError (parseWhereCondition "(title=\"say \\\"hi\\\"\")")+  assertBool+    "escaped quotes match"+    (case quoted of PredicateWhere predicate -> matches predicate scalars; LegacyWhere _ -> False)++  -- A record inside a list is ignored; its scalar siblings still count.+  assertBool "cli is forbidden" (not (matches (PredicateNotEquals (key "tags") "cli") mixed))+  assertBool "other is not present" (matches (PredicateNotIn (key "tags") ("other" :| [])) mixed)+  assertBool "cli is included" (matches (PredicateIn (key "tags") ("cli" :| [])) mixed)++-- | Every operand of a predicate is checked, with the legacy checker's scope+-- rules, below @not@ and on both sides of @or@.+testCheckPredicateAgainstProfile :: IO (Either Text ())+testCheckPredicateAgainstProfile = do+  descriptorPath <- fixtureFilePath "profiles/concept-filters.dhall"+  loaded <- loadProfileFile descriptorPath+  pure $ do+    spec <- first ("failed to load concept-filter profile: " <>) loaded+    compiled <- firstShow (compileProfile spec)+    openTypes <- firstShow (compileProfile (spec & #allowUnknownTypes .~ True))+    let status = TopLevelField "status"+        statusError value = FilterValueNotInVocabulary status value ["proposed", "accepted", "completed", "rejected"]+        equals selector value = PredicateAtom (FieldEquals selector value)+        checkAll = checkPredicateAgainstProfile compiled []+        checkFor = checkPredicateAgainstProfile compiled++    -- Negative values and set members outside a closed vocabulary. 'status'+    -- is also a core key, so this guards the declaration-before-core order.+    assertEqual [statusError "acepted"] (checkAll (PredicateNotEquals status "acepted"))+    assertEqual [] (checkAll (PredicateNotEquals status "accepted"))+    assertEqual [statusError "acepted"] (checkAll (PredicateNotIn status ("completed" :| ["acepted"])))+    assertEqual [statusError "proposd"] (checkAll (PredicateIn status ("accepted" :| ["proposd"])))+    -- Below not and on a branch of or that would match everything.+    assertEqual [statusError "acepted"] (checkAll (PredicateNot (equals status "acepted")))+    assertEqual+      [statusError "acepted"]+      (checkAll (PredicateOr (PredicateAtom (FieldAbsent status)) (PredicateNot (equals status "acepted"))))+    -- Once each, in written order, undeclared keys included.+    assertEqual+      [statusError "acepted"]+      (checkAll (PredicateAnd (PredicateNotEquals status "acepted") (PredicateNotEquals status "acepted")))+    assertEqual+      [FilterFieldNotDeclared (TopLevelField "statuz"), statusError "acepted"]+      ( checkAll+          ( PredicateOr+              (PredicateIn (TopLevelField "statuz") ("x" :| ["y"]))+              (PredicateNotEquals status "acepted")+          )+      )+    assertEqual+      [FilterFieldNotDeclared (TopLevelField "statuz")]+      (checkAll (PredicateNot (PredicateAtom (FieldPresent (TopLevelField "statuz")))))+    -- The core-key fallback and an open nested vocabulary accept anything.+    assertEqual [] (checkAll (PredicateNotEquals (TopLevelField "timestamp") "anything"))+    assertEqual [] (checkAll (PredicateNotIn (NestedField "reviews" "reviewer") ("anyone" :| [])))+    -- A closed nested vocabulary.+    assertEqual+      [FilterValueNotInVocabulary (NestedField "reviews" "outcome") "approvd" ["approved", "changes-requested", "commented"]]+      (checkAll (PredicateNotIn (NestedField "reviews" "outcome") ("approvd" :| [])))+    -- The scope trap: noteKind is closed on Note alone.+    assertEqual+      [FilterValueNotInVocabulary (TopLevelField "noteKind") "bogus" ["scratch", "reference"]]+      (checkFor ["Note"] (PredicateNotEquals (TopLevelField "noteKind") "bogus"))+    assertEqual [] (checkAll (PredicateNotEquals (TopLevelField "noteKind") "bogus"))+    -- A type equality inside an expression narrows nothing.+    assertEqual+      []+      (checkAll (PredicateAnd (equals (TopLevelField "type") "Note") (equals (TopLevelField "noteKind") "bogus")))+    -- Requested types restrict declarations.+    assertEqual+      [FilterFieldNotDeclared (TopLevelField "targetPlan")]+      (checkFor ["Note"] (PredicateNot (PredicateAtom (FieldPresent (TopLevelField "targetPlan")))))+    -- Type names are the vocabulary of type unless unknown types are allowed.+    assertEqual+      [FilterValueNotInVocabulary (TopLevelField "type") "Ghost" ["Improvement Request", "Note"]]+      (checkAll (PredicateNotEquals (TopLevelField "type") "Ghost"))+    assertEqual [] (checkPredicateAgainstProfile openTypes [] (PredicateNotEquals (TopLevelField "type") "Ghost"))+    -- A contradiction is not an error.+    assertEqual [] (checkAll (PredicateAnd (equals status "accepted") (equals status "proposed")))++fixturePath :: FilePath -> IO FilePath+fixturePath name = do+  let candidates =+        [ "okf-core" </> "test" </> "fixtures" </> name,+          "test" </> "fixtures" </> name+        ]+  findExisting candidates+  where+    findExisting [] = fail ("fixture not found: " <> name)+    findExisting (candidate : rest) = do+      exists <- doesDirectoryExist candidate+      if exists then pure candidate else findExisting rest++requireConcept :: Text -> [Concept] -> Either Text Concept+requireConcept rawId concepts = do+  conceptId <- firstShow (parseConceptId rawId)+  case findConcept conceptId concepts of+    Just concept -> Right concept+    Nothing -> Left ("missing concept " <> rawId)++requireConceptIO :: Text -> [Concept] -> IO Concept+requireConceptIO rawId concepts =+  case requireConcept rawId concepts of+    Right concept -> pure concept+    Left message -> fail (Text.unpack message)++withFixtureBundle :: (FilePath -> IO (Either Text ())) -> IO (Either Text ())+withFixtureBundle action = do+  temporaryDirectory <- getTemporaryDirectory+  root <- createTempDirectory temporaryDirectory "okf-core-test"+  createFixtureBundle root+  result <- action root+  removeDirectoryRecursive root+  pure result++createFixtureBundle :: FilePath -> IO ()+createFixtureBundle root = do+  createDirectoryIfMissing True (root </> "datasets")+  createDirectoryIfMissing True (root </> "tables")+  Text.IO.writeFile (root </> "index.md") "# Reserved root index\n"+  Text.IO.writeFile (root </> "tables" </> "index.md") "# Reserved tables index\n"+  Text.IO.writeFile (root </> "tables" </> "log.md") "# Reserved log\n"+  Text.IO.writeFile+    (root </> "datasets" </> "sales.md")+    (fixtureDocument "Dataset" "Sales" "Sales dataset." "")+  Text.IO.writeFile+    (root </> "tables" </> "customers.md")+    (fixtureDocument "BigQuery Table" "Customers" "Customer records." "")+  Text.IO.writeFile+    (root </> "tables" </> "orders.md")+    ( fixtureDocument+        "BigQuery Table"+        "Orders"+        "Order records."+        ( Text.unlines+            [ "[Customers absolute](/tables/customers.md)",+              "[Customers relative](./customers.md)",+              "[Sales relative](../datasets/sales.md)",+              "[Broken](/missing.md)",+              "[External](https://example.com/x.md)"+            ]+        )+    )++fixtureDocument :: Text -> Text -> Text -> Text -> Text+fixtureDocument typeName titleText descriptionText documentBody =+  Text.unlines+    [ "---",+      "type: " <> typeName,+      "title: " <> titleText,+      "description: " <> descriptionText,+      "timestamp: 2026-06-16T00:00:00Z",+      "---",+      "",+      documentBody+    ]++-- These imports must continue to mean the selected profile after relocation.+testBootstrapRoundTrip :: IO (Either Text ())+testBootstrapRoundTrip = do+  registry <- fixtureFilePath "registry/package.dhall" >>= makeAbsolute+  descriptor <- fixtureFilePath "profiles/decisions.dhall" >>= makeAbsolute+  temp <- getTemporaryDirectory+  bracket (createTempDirectory temp "okf-bootstrap") removeDirectoryRecursive $ \root -> do+    createDirectoryIfMissing True (root </> "physical" </> "unused")+    createDirectoryLink (root </> "physical") (root </> "alias")+    let destination = root </> "alias" </> "unused" </> ".." </> "bundle space 日本語"+        localSource = root </> "source space 日本語.dhall"+    -- A source filename also needs Dhall component quoting.+    sourceText <- renderBootstrapDescriptor root (ImportDescriptorFile descriptor)+    case sourceText of+      Left err -> pure (Left (renderBootstrapError err))+      Right contents -> do+        Text.IO.writeFile localSource contents+        results <- for+          [ (ImportRegistryFile registry "postgresql", RegistryFile registry, "postgresql"),+            (ImportRegistryFile registry "nested.decisions", RegistryFile registry, "nested.decisions"),+            (ImportRegistryFile descriptor "", RegistryFile descriptor, ""),+            (ImportDescriptorFile localSource, RegistryFile descriptor, "")+          ]+          $ \(source, ref, selected) -> do+            rendered <- renderBootstrapDescriptor destination source+            case rendered of+              Left err -> pure (Left (renderBootstrapError err))+              Right contents' -> do+                createDirectoryIfMissing True destination+                Text.IO.writeFile (destination </> "profile.dhall") contents'+                actual <- loadProfileFile (destination </> "profile.dhall")+                expected <- loadRegistry ref+                pure $ do+                  assertBootstrapComments contents'+                  entries <- expected+                  entry <- maybe (Left "missing export") Right (findRegistryEntry selected entries)+                  assertEqual (Right (entry ^. #spec)) actual+        pure (sequence_ results)++testBootstrapExpressions :: IO (Either Text ())+testBootstrapExpressions = do+  let hash = "sha256:" <> Text.replicate 64 "0"+      reference = "https://example.invalid/package.dhall " <> hash+      render expression selected = renderBootstrapDescriptor "/tmp" (ImportRegistryExpression expression selected)+  hashed <- render reference "a.b"+  escaped <- render reference "foo bar"+  relative <- render "./registry/package.dhall" "x"+  header <- render ("https://example.invalid/package.dhall using ./headers.dhall " <> hash) "x"+  malformed <- render "let =" "x"+  multiline <- render (reference <> "\n-- metadata  \t\n  \t\n--   indented  text\t \n") "x"+  environment <- render "env:OKF_BOOTSTRAP_TEST_UNSET" ""+  location <- render "https://example.invalid/package.dhall as Location" ""+  pure $ do+    contents <- first renderBootstrapError hashed+    assertBootstrapComments contents+    assertBool "hash preserved" (hash `Text.isInfixOf` contents)+    assertBool "nested selection" ("registry.a.b" `Text.isSuffixOf` Text.stripEnd contents)+    escapedText <- first renderBootstrapError escaped+    assertBool "escaped label" ("registry.`foo bar`" `Text.isInfixOf` escapedText)+    assertBool "relative import rejected" (case relative of Left RelativeExpressionImport {} -> True; _ -> False)+    assertBool "relative header import rejected" (case header of Left RelativeExpressionImport {} -> True; _ -> False)+    assertBool "parse failure classified" (case malformed of Left DescriptorParseError {} -> True; _ -> False)+    multilineText <- first renderBootstrapError multiline+    assertBootstrapComments multilineText+    assertBool "meaningful comment indentation retained" ("-- --   indented  text\n" `Text.isInfixOf` multilineText)+    assertBool "multiline metadata remains a comment" (case Dhall.exprFromText "descriptor" multilineText of Right _ -> True; _ -> False)+    locationText <- first renderBootstrapError location+    assertBootstrapComments locationText+    assertBool "location import preserved" ("as Location" `Text.isInfixOf` locationText)+    environmentText <- first renderBootstrapError environment+    assertBootstrapComments environmentText+    assertBool "environment import and live guidance retained" (all (`Text.isInfixOf` environmentText) ["env:OKF_BOOTSTRAP_TEST_UNSET", "Local and environment inputs remain live"])+    assertBool "environment descriptor parses without reading input" (case Dhall.exprFromText "descriptor" environmentText of Right _ -> True; _ -> False)++assertBootstrapComments :: Text -> Either Text ()+assertBootstrapComments contents = do+  let comments = filter (Text.isPrefixOf "--") (Text.lines contents)+  assertBool "descriptor comments present" (not (null comments))+  assertBool "empty comments use bare dashes" ("--" `elem` comments)+  for_ comments $ \line ->+    assertBool+      ("comment has trailing whitespace: " <> line)+      (not (" " `Text.isSuffixOf` line || "\t" `Text.isSuffixOf` line))+  assertBool+    "descriptor explanation remains readable"+    ( all+        (`Text.isInfixOf` contents)+        ["-- OKF profile descriptor written by `okf profile init`.", "-- Profile:", "-- Source:  "]+    )++testBootstrapPure :: Either Text ()+testBootstrapPure = do+  assertEqual "../c/f.dhall" (relativeImportPath "/a/b" "/a/c/f.dhall")+  assertEqual "./f.dhall" (relativeImportPath "/a/b" "/a/b/f.dhall")+  assertEqual "./c/d/f.dhall" (relativeImportPath "/a/b" "/a/b/c/d/f.dhall")+  let spec = testProfileSpec & #okfVersion .~ "0.1" & #requireBundleVersion .~ Just "0.2"+  assertEqual (parseOkfVersion "0.2") (bootstrapOkfVersion Nothing spec)+  assertEqual (parseOkfVersion "0.3") (bootstrapOkfVersion (parseOkfVersion "0.3") spec)+  assertEqual (parseOkfVersion "0.1") (bootstrapOkfVersion Nothing (spec & #requireBundleVersion .~ Just "bad"))++testCatchSynchronous :: IO (Either Text ())+testCatchSynchronous = do+  synchronous <- catchSynchronous (ioError (userError "expected IO failure")) (\_ -> pure True)+  asynchronous <- try @AsyncException (catchSynchronous (throwIO UserInterrupt) (\_ -> pure False))+  pure $ if synchronous && asynchronous == Left UserInterrupt then Right () else Left "asynchronous cancellation was swallowed"++-- Regression matrix for bounded same-concept constraints. The descriptor is+-- loaded through both public decoders; mutations are independent concepts.+testProductDiscoveryConstraints :: IO (Either Text ())+testProductDiscoveryConstraints = do+  path <- fixtureFilePath "profiles/product-discovery.dhall"+  oldPath <- fixtureFilePath "profiles/pre-product-discovery-0.10.0.0.dhall"+  loaded <- loadProfileFile path+  registry <- loadRegistry (RegistryFile path)+  registryPath <- fixtureFilePath "profiles/product-discovery-registry.dhall"+  namedRegistry <- loadRegistry (RegistryFile registryPath)+  old <- loadProfileFile oldPath+  oldRegistry <- loadRegistry (RegistryFile oldPath)+  malformedPath <- fixtureFilePath "profiles/product-discovery-malformed.dhall"+  malformed <- loadRegistry (RegistryFile malformedPath)+  pure $ do+    spec <- loaded+    malformedEntries <- firstShow malformed+    assertEqual [] malformedEntries+    compiled <- firstShow (compileProfile spec)+    named <- firstShow namedRegistry+    assertEqual ["productDiscovery"] (map (^. #export) named)+    assertEqual [spec] (map (^. #spec) named)+    entries <- firstShow registry+    assertEqual [spec] (map (^. #spec) entries)+    oldSpec <- old+    _ <- firstShow (compileProfile oldSpec)+    oldEntries <- firstShow oldRegistry+    assertEqual [oldSpec] (map (^. #spec) oldEntries)+    assertEqual (Just "Frozen guidance") (oldSpec ^. #guidance)+    let arr = toJSON :: [Value] -> Value+        rec = object+        outcome fields = ("outcomes", arr [rec fields])+        complete = [("metric", String "duration"), ("unit", String "s"), ("direction", String "down"), ("method", String "observe")]+        check fields = do+          concept <- profileConcept "one" (("type", String "Job") : fields) ""+          pure (validateProfile PermissiveConformance compiled [concept])+        passes fields = check fields >>= assertEqual []+        fails fields = do+          violations <- check fields+          if null violations then Left ("expected rejection: " <> Text.pack (show fields)) else Right ()+        hasPath expected violations =+          if any (Text.isInfixOf expected . Text.pack . show) violations then Right () else Left ("missing path " <> expected <> ": " <> Text.pack (show violations))+    passes [outcome [("name", String "qualitative")]]+    passes [outcome complete]+    for_ ["metric", "unit", "direction", "method", "baseline", "target", "population", "period"] $ \key ->+      fails [outcome [(key, if key `elem` ["baseline", "target"] then Number 0 else String "usable")]]+    let measured = complete <> [("baseline", Number 0), ("population", String "authors"), ("period", String "week")]+    fails [outcome measured]+    passes [outcome measured, ("sources", arr [String "interview"])]+    passes [outcome (complete <> [("target", Number 2)])]+    for_ [Number 0, Number (-2), Number 1.25, Number 1e400] $ \n -> passes [outcome (complete <> [("target", n)])]+    for_ [Bool True, String "1.25", Null] $ \n -> fails [outcome (complete <> [("target", n)])]+    passes [("outcomeRefs", arr [rec [("outcomeNames", arr [])]])]+    fails [("outcomeRefs", arr [rec [("outcomeNames", arr [String "faster"])]])]+    for_ ["planned", "in-progress", "delivered"] $ \status -> do+      fails [("status", String status)]+      passes [("status", String status), ("features", arr [rec []])]+      passes [("status", String status), ("featureRefs", arr [String "f"])]+      fails [("status", String status), ("features", arr []), ("featureRefs", arr [])]+      fails [("status", String status), ("features", arr [Number 1])]+    passes [("status", String "draft")]+    let period a b = outcome [("periodStart", String a), ("periodEnd", String b)]+    passes [period "2026-10-01T00:00:00.1Z" "2026-10-01T00:00:00.2Z"]+    fails [period "2026-10-01T00:00:00Z" "2026-10-01T00:00:00Z"]+    fails [period "2026-10-02T00:00:00Z" "2026-10-01T00:00:00Z"]+    passes [outcome [("periodStart", String "2026-10-02T00:00:00Z")]]+    passes [("outcomes", arr [rec [("periodStart", String "2026-10-02T00:00:00Z")], rec [("periodEnd", String "2026-10-01T00:00:00Z")]])]+    fails [period "bad" "2026-10-01T00:00:00Z"]+    passes [("jobs", arr [rec [("name", String "author")]]), ("features", arr [rec [("jobs", arr [String "author"])]])]+    fails [("features", arr [rec [("jobs", arr [String "unknown"])]])]+    for_ [Number 42, Bool True, Null, rec [], arr []] $ \bad -> do+      fails [("jobs", arr [rec [("name", bad)]])]+      vs <- check [("features", arr [rec [("jobs", arr [bad])]])]+      hasPath "ArrayIndex 0" vs+      fails [("jobRefs", arr [bad])]+      fails [("featureRefs", arr [bad])]+      fails [("features", arr [rec [("featureRef", bad)]])]+    vs <- check [("jobs", arr [rec [("name", Number 42)]]), ("features", arr [rec [("jobs", arr [String "unknown", Number 7])]])]+    assertEqual 3 (length vs)+    fails [("jobs", arr [rec [("name", String " ")]])]+    for_ [[("featureRefs", arr [String "f", String "f"])], [("features", arr [rec [("featureRef", String "f")], rec [("featureRef", String "f")]])], [("featureRefs", arr [String "f"]), ("features", arr [rec [("featureRef", String "f")]])]] fails+    one <- profileConcept "one" [("featureRefs", arr [String "f"])] ""+    two <- profileConcept "two" [("featureRefs", arr [String "f"])] ""+    assertEqual [] (validateProfile PermissiveConformance compiled [one, two])+    let select key = ValueSelector key Nothing+        root = spec ^. #frontmatter+        invalid rootRules = case compileProfile (spec & #frontmatter .~ rootRules) of+          Left _ -> Right ()+          Right _ -> Left "expected constraint definition failure"+        pc = PresenceConstraint Nothing [] [] []+    invalid (root & #presenceConstraints .~ [pc])+    invalid (root & #presenceConstraints .~ [pc & #requireAll .~ [select "unknown"]])+    invalid (root & #presenceConstraints .~ [pc & #requireAll .~ [ValueSelector "outcomes" (Just "baseline")]])+    invalid (root & #membershipConstraints .~ [MembershipConstraint (select "jobRefs") (select "jobRefs")])+    invalid (root & #membershipConstraints .~ [MembershipConstraint (ValueSelector "outcomes" (Just "baseline")) (select "jobRefs")])+    invalid (root & #uniqueValuesConstraints .~ [UniqueValuesConstraint [select "featureRefs", select "featureRefs"]])+    invalid (root & #timestampOrderConstraints .~ [TimestampOrderConstraint "status" "status"])+    invalid (root & #presenceConstraints .~ [PresenceConstraint (Just (FieldCondition "jobRefs" ["x"])) [] [select "sources"] []])+    let baseConstraints = compiledProfileBaseConstraints compiled+    assertEqual baseConstraints (compiledProfileConstraintsForType compiled "unknown")+    assertEqual 2 (length (conceptPresenceConstraints baseConstraints))+    let withoutRelations = spec & #frontmatter . #membershipConstraints .~ [] & #frontmatter . #uniqueValuesConstraints .~ []+    loose <- firstShow (compileProfile withoutRelations)+    numeric <- profileConcept "numeric" [("jobs", arr [rec [("name", Number 42)]])] ""+    assertEqual [] (validateProfile PermissiveConformance loose [numeric])+    -- Merge conjunction, exact deduplication, and nested constraints shared by+    -- the two accepted record spellings.+    let sourceRule = fieldRule "sources" Nothing [] List Nothing Nothing Nothing Nothing+        objectMembers = NestedRules True [] [] [nestedFieldRule "value" Nothing [] Scalar Nothing Nothing Nothing] [] []+        obj = (fieldRule "context" Nothing [] Any Nothing Nothing Nothing Nothing) & #objectFields .~ Just objectMembers+        p = PresenceConstraint Nothing [ValueSelector "outcomes" (Just "name")] [select "context"] []+        objectSpec = spec & #frontmatter . #optional %~ (obj :) & #frontmatter . #presenceConstraints .~ [p]+    objectCompiled <- firstShow (compileProfile objectSpec)+    let objectCheck value = do+          concept <- profileConcept "one" [outcome [("name", String "x")], ("context", value)] ""+          pure (validateProfile PermissiveConformance objectCompiled [concept])+    objectCheck (rec [("value", String "x")]) >>= assertEqual []+    emptyObject <- objectCheck (rec [])+    assertEqual 1 (length emptyObject)+    let rootConstraint = PresenceConstraint Nothing [select "jobRefs"] [select "sources"] []+        rootOnly = emptyTestFrontmatterRules & #optional .~ [sourceRule, fieldRule "jobRefs" Nothing [] List Nothing Nothing Nothing Nothing] & #presenceConstraints .~ [rootConstraint]+        typeRule = head (testProfileSpec ^. #types) & #frontmatter .~ rootOnly & #pathPattern .~ Nothing & #resourceScheme .~ Nothing & #requireSchemaSection .~ False & #idPrefix .~ Nothing+        mergedSpec = spec & #frontmatter .~ rootOnly & #types .~ [typeRule]+    merged <- firstShow (compileProfile mergedSpec)+    assertEqual [rootConstraint] (conceptPresenceConstraints (compiledProfileConstraintsForType merged (typeRule ^. #type_)))+    let selectedRule = fieldRule "items" Nothing [] List Nothing Nothing Nothing Nothing+        dedupRoot =+          emptyTestFrontmatterRules+            & #optional+            .~ [selectedRule, sourceRule, fieldRule "jobRefs" Nothing [] List Nothing Nothing Nothing Nothing]+            & #membershipConstraints+            .~ [MembershipConstraint (select "items") (select "sources"), MembershipConstraint (select "items") (select "jobRefs")]+    dedupCompiled <- firstShow (compileProfile (spec & #frontmatter .~ dedupRoot))+    badConcept <- profileConcept "bad" [("items", arr [Number 1, Null, rec [], arr []])] ""+    assertEqual 4 (length (validateProfile PermissiveConformance dedupCompiled [badConcept]))+    -- Projected list presence observes the list once; sibling requirements stay+    -- correlated with their own record rather than borrowing from another.+    let projected = PresenceConstraint Nothing [ValueSelector "features" (Just "jobs")] [select "sources"] []+    projectedCompiled <- firstShow (compileProfile (spec & #frontmatter . #presenceConstraints .~ [projected]))+    projectedConcept <- profileConcept "projected" [("features", arr [rec [("jobs", arr [String "author"])]])] ""+    let projectedViolations = validateProfile PermissiveConformance projectedCompiled [projectedConcept]+    if any (\case ConstraintPresenceMissing {} -> True; _ -> False) projectedViolations then Right () else Left "projected whole-list trigger was lost"+    correlated <- check [("outcomeRefs", arr [rec [("outcomeNames", arr [String "faster"])], rec [("jobRef", String "JOB-1")]]), ("jobRefs", arr [String "JOB-1"])]+    assertEqual 1 (length correlated)+    let timestamps = [fieldRule key Nothing [] Scalar (Just Rfc3339Utc) Nothing Nothing Nothing | key <- ["start", "end"]]+        times = emptyTestFrontmatterRules & #optional .~ timestamps & #timestampOrderConstraints .~ [TimestampOrderConstraint "start" "end"]+    rootTimes <- firstShow (compileProfile (spec & #frontmatter .~ times))+    timeConcept <- profileConcept "time" [("start", String "2026-10-02T00:00:00Z"), ("end", String "2026-10-01T00:00:00Z")] ""+    assertEqual 1 (length (validateProfile PermissiveConformance rootTimes [timeConcept]))+    assertEqual 2 (Map.size (conceptResolvedSelectors (compiledProfileBaseConstraints rootTimes)))+    for_ [".inf", "-.inf", ".nan"] $ \spelling ->+      case testConceptWithFrontmatter "nonfinite" ("type: Job\noutcomes: [{metric: duration, unit: s, direction: down, method: observe, target: " <> spelling <> "}]\n") of+        Left _ -> Right () -- parser rejection is an accepted outcome+        Right concept -> if null (validateProfile PermissiveConformance compiled [concept]) then Left "nonfinite YAML accepted" else Right ()+    invalid (root & #membershipConstraints .~ [MembershipConstraint (select "jobs") (select "jobRefs")])+    invalid (root & #membershipConstraints .~ [MembershipConstraint (ValueSelector "jobs" (Just "unknown")) (select "jobRefs")])+    invalid (root & #presenceConstraints .~ [pc & #requireAll .~ [select "sources", select "sources"]])+    invalid (root & #presenceConstraints .~ [pc & #requireAll .~ [select ""]])+    let siblingA = nestedFieldRule "a" Nothing [] Scalar Nothing Nothing Nothing+        siblingB = nestedFieldRule "b" Nothing [] Scalar Nothing Nothing Nothing+        recordGate = PresenceConstraint Nothing [select "b"] [select "a"] []+        elementRules = NestedRules True [] [] [siblingA, siblingB] [recordGate] []+        objectRules = NestedRules True [] [] [siblingA, siblingB] [] []+        dual = (fieldRule "dual" Nothing [] Any Nothing (Just elementRules) Nothing Nothing) & #objectFields .~ Just objectRules+        dualSpec = spec & #frontmatter .~ (emptyTestFrontmatterRules & #optional .~ [dual])+    dualCompiled <- firstShow (compileProfile dualSpec)+    dualRule <- maybe (Left "dual field missing") Right (Map.lookup "dual" (compiledProfileBaseRules dualCompiled))+    assertEqual (fieldRuleElementConstraints dualRule) (fieldRuleObjectConstraints dualRule)+    assertEqual [recordGate] (conceptPresenceConstraints (fieldRuleObjectConstraints dualRule))+    for_ [rec [("b", String "present")], arr [rec [("b", String "present")]]] $ \value -> do+      concept <- profileConcept "dual" [("dual", value)] ""+      assertEqual 1 (length (validateProfile PermissiveConformance dualCompiled [concept]))+    rendered <- firstShow (renderProfileDocumentation defaultDocumentationOptions dualCompiled)+    let prose = Text.concat (map serializeConcept rendered)+    assertEqual 1 (length (Text.breakOnAll "require all [a]" prose))++-- Exercise exact file decoding, width-extracting registry decoding, and local+-- discovery; the root-level closure flag in the frozen fixture is intentional.+testNestedClosureDecoding :: IO (Either Text ())+testNestedClosureDecoding = do+  currentPath <- fixtureFilePath "profiles/nested-closure.dhall"+  oldPath <- fixtureFilePath "profiles/pre-nested-closure.dhall"+  registryPath <- fixtureFilePath "profiles/nested-closure-registry.dhall"+  malformedPath <- fixtureFilePath "profiles/nested-closure-malformed.dhall"+  current <- loadProfileFile currentPath+  old <- loadProfileFile oldPath+  registry <- loadRegistry (RegistryFile registryPath)+  oldRegistry <- loadRegistry (RegistryFile oldPath)+  malformed <- loadRegistry (RegistryFile malformedPath)+  malformedFile <- loadProfileFile malformedPath+  malformedTypePath <- fixtureFilePath "profiles/nested-closure-malformed-type.dhall"+  malformedType <- loadRegistry (RegistryFile malformedTypePath)+  discovered <- traverse ProfileDiscovery.fileQualifiesAsProfileDescriptor [currentPath, oldPath, malformedPath]+  pure $ do+    spec <- current+    oldSpec <- old+    compiled <- firstShow (compileProfile spec)+    oldCompiled <- firstShow (compileProfile oldSpec)+    entries <- firstShow registry+    assertEqual ["nestedClosure"] (map (^. #export) entries)+    assertEqual [spec] (map (^. #spec) entries)+    historical <- firstShow oldRegistry+    assertEqual [oldSpec] (map (^. #spec) historical)+    assertEqual [True, True, False] discovered+    assertEqual False (oldSpec ^. #allowUnknownFields)+    assertEqual [] =<< firstShow malformed+    assertEqual [] =<< firstShow malformedType+    case malformedFile of+      Left _ -> Right ()+      Right _ -> Left "malformed descriptor loaded through a frozen decoder"+    for_ [compiledProfileBaseRules compiled, compiledProfileRulesForType compiled "Note"] $ \rules -> do+      rows <- lookupCompiledRule "rows" rules+      assertEqual (Just False) (fieldRuleElementAllowsUnknownFields rows)+    rendered <- firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)+    let documentation = Text.concat (map serializeConcept rendered)+    for_ ["- Element field names: closed", "- Object field names: closed", "- Element field names: none", "note"] $ \expected ->+      assertBool ("missing compiled documentation: " <> expected) (expected `Text.isInfixOf` documentation)+    assertEqual rendered =<< firstShow (renderProfileDocumentation defaultDocumentationOptions compiled)+    for_ [compiledProfileBaseRules oldCompiled, compiledProfileRulesForType oldCompiled "Note"] $ \rules -> do+      rows <- lookupCompiledRule "rows" rules+      settings <- lookupCompiledRule "settings" rules+      assertEqual (Just True) (fieldRuleElementAllowsUnknownFields rows)+      assertEqual (Just True) (fieldRuleObjectAllowsUnknownFields settings)+      for_ [fieldRuleElementConstraints rows, fieldRuleObjectConstraints settings] $ \constraints -> do+        assertEqual 1 (length (conceptPresenceConstraints constraints))+        assertEqual [TimestampOrderConstraint "start" "end"] (conceptTimestampOrderConstraints constraints)+      score <- maybe (Left "frozen nested members missing") (lookupCompiledRule "score") (fieldRuleElementFields rows)+      assertEqual (Just FiniteDecimal) (fieldRuleFormat score)+    for_ [compiledProfileBaseConstraints oldCompiled, compiledProfileConstraintsForType oldCompiled "Note"] $ \constraints -> do+      assertEqual 1 (length (conceptPresenceConstraints constraints))+      assertEqual 1 (length (conceptTimestampOrderConstraints constraints))+      assertEqual 1 (length (conceptMembershipConstraints constraints))+      assertEqual 1 (length (conceptUniqueValuesConstraints constraints))++-- A public diagnostic slice: one supplied unknown key, independent of values.+testNestedClosureValidation :: Either Text ()+testNestedClosureValidation = do+  let members = NestedRules False [nestedFieldRule "name" Nothing [] Scalar Nothing Nothing Nothing] [] [] [] []+      spec = nestedProfileWithRules Any members Nothing+      validate rawSpec fields = do+        compiled <- firstShow (compileProfile rawSpec)+        concept <- profileConcept "one" (("type", String "Reviewed Concept") : fields) ""+        pure (validateProfile PermissiveConformance compiled [concept])+      row values = ("reviews", toJSON [object values])+  cid <- firstShow (parseConceptId "one")+  violations <- validate spec [row ["name" .= ("a" :: Text), "stray" .= ("x" :: Text)]]+  assertEqual [NestedFieldNotInProfile cid (FieldPath (FieldName "reviews" :| [ArrayIndex 0, FieldName "stray"]))] violations+  assertEqual [] =<< validate spec [row ["name" .= ("a" :: Text)]]+  let open = members & #allowUnknownFields .~ True+      declared = members & #optional .~ [nestedFieldRule "stray" Nothing [] Scalar Nothing Nothing Nothing]+  for_ [open, declared] $ \rules ->+    assertEqual [] =<< validate (nestedProfileWithRules Any rules Nothing) [row ["name" .= ("a" :: Text), "stray" .= ("x" :: Text)]]++-- The matrix isolates scope merging, record shape, and presence from closure.+testNestedClosureMatrix :: Either Text ()+testNestedClosureMatrix = do+  cid <- firstShow (parseConceptId "one")+  let scalar key = nestedFieldRule key Nothing [] Scalar Nothing Nothing Nothing+      rules policy names = NestedRules policy [] [] (map scalar names) [] []+      parent elements objects = (requiredField "value") & #elementFields .~ elements & #objectFields .~ objects+      front field = emptyTestFrontmatterRules & #optional .~ [field]+      specFor elements objects = objectProfileWithRules "value" Any objects elements & #okfVersion .~ "0.2"+      typed base field = base & #types .~ [TypeRule "Note" Nothing Nothing (front field) Nothing Nothing False [] Nothing]+      record = object . map (\key -> (key, String "present"))+      array :: [Value] -> Value+      array values = toJSON values+      validate mode spec values = do+        compiled <- firstShow (compileProfile spec)+        concept <- profileConcept "one" values ""+        pure (validateProfile mode compiled [concept])+      check spec value = validate PermissiveConformance spec [("type", String "Note"), ("value", value)]+      unknowns = mapMaybe (\case NestedFieldNotInProfile _ path -> Just path; _ -> Nothing)+      path segments = FieldPath (FieldName "value" :| segments)+      violationsFor shape key = [path (if shape then [ArrayIndex 0, FieldName key] else [FieldName key])]+      shapeValue shape value = if shape then array [value] else value+      inspect shape = if shape then fieldRuleElementAllowsUnknownFields else fieldRuleObjectAllowsUnknownFields+      shapeRules shape = if shape then fieldRuleElementFields else fieldRuleObjectFields+      mkParent shape r = if shape then parent (Just r) Nothing else parent Nothing (Just r)+      mkSpec shape r = if shape then specFor (Just r) Nothing else specFor Nothing (Just r)+  noShapeCompiled <- firstShow (compileProfile (specFor Nothing Nothing))+  noShapeRule <- lookupCompiledRule "value" (compiledProfileBaseRules noShapeCompiled)+  assertEqual Nothing (fieldRuleElementAllowsUnknownFields noShapeRule)+  assertEqual Nothing (fieldRuleObjectAllowsUnknownFields noShapeRule)+  for_ [True, False] $ \shape -> do+    -- All boolean pairs, union of names, absence as identity, and unknown types.+    for_ [(a, b) | a <- [True, False], b <- [True, False]] $ \(a, b) -> do+      let base = mkSpec shape (rules a ["base"])+          spec = typed base (mkParent shape (rules b ["typed"]))+      compiled <- firstShow (compileProfile spec)+      effective <- lookupCompiledRule "value" (compiledProfileRulesForType compiled "Note")+      assertEqual (Just (a && b)) (inspect shape effective)+      members <- maybe (Left "expected nested map") Right (shapeRules shape effective)+      assertEqual ["base", "typed"] (Map.keys members)+      assertEqual [] =<< check spec (shapeValue shape (record ["base", "typed"]))+      rejected <- check spec (shapeValue shape (record ["base", "typed", "stray"]))+      assertEqual (if a && b then [] else violationsFor shape "stray") (unknowns rejected)+      for_ [typed base (requiredField "value"), typed (specFor Nothing Nothing) (mkParent shape (rules a ["base"]))] $ \identitySpec -> do+        identityCompiled <- firstShow (compileProfile identitySpec)+        identityRule <- lookupCompiledRule "value" (compiledProfileRulesForType identityCompiled "Note")+        assertEqual (Just a) (inspect shape identityRule)+      unknownType <- validate PermissiveConformance spec [("type", String "Unknown"), ("value", shapeValue shape (record ["base", "typed"]))]+      assertEqual (if a then [] else violationsFor shape "typed") (unknowns unknownType)+    for_ [True, False] $ \open -> do+      emptyCompiled <- firstShow (compileProfile (mkSpec shape (rules open [])))+      emptyRule <- lookupCompiledRule "value" (compiledProfileBaseRules emptyCompiled)+      assertEqual (Just open) (inspect shape emptyRule)+      emptyDocumentation <- firstShow (renderProfileDocumentation defaultDocumentationOptions emptyCompiled)+      let expected = (if shape then "- Element field names: " else "- Object field names: ") <> if open then "open" else "closed"+      assertBool "empty map lost closure in documentation" (expected `Text.isInfixOf` Text.concat (map serializeConcept emptyDocumentation))+    -- An empty closed declaration forbids every member, including core/ID names.+    let closedEmpty = mkSpec shape (rules False []) & #idField .~ Just "docId"+    rejected <- check closedEmpty (shapeValue shape (record ["title", "docId"]))+    assertEqual (map (\key -> head (violationsFor shape key)) ["docId", "title"]) (unknowns rejected)+    for_ [[], [("value", shapeValue shape (object []))], [("value", if shape then array [] else object [])]] $ \values -> do+      absent <- validate StrictAuthoring closedEmpty (("type", String "Note") : values)+      assertEqual [] (unknowns absent)+      -- Required parent remains missing; a list containing an empty record is present.+      assertEqual (if shape && values == [("value", array [object []])] then [] else [MissingProfileField cid "value" Nothing]) absent+    -- The same declared rules work for either shape and retain ordinary checks.+    let kind = (scalar "kind") & #allowedValues .~ ["human", "model"]+        conditional = FieldCondition "kind" ["model"]+        provider = (scalar "provider") & #when .~ Just conditional & #allowedValues .~ ["openai"]+        recommended = (scalar "audit") & #when .~ Just conditional+        conditionalRules = NestedRules False [kind, provider] [recommended] [scalar "note"] [] []+        conditionalSpec = mkSpec shape conditionalRules+        human = object ["kind" .= ("human" :: Text), "provider" .= ("openai" :: Text), "audit" .= True, "note" .= ("ok" :: Text)]+    assertEqual [] =<< check conditionalSpec (shapeValue shape human)+    invalidKnown <- check conditionalSpec (shapeValue shape (object ["kind" .= ("human" :: Text), "provider" .= ("bad" :: Text)]))+    assertEqual [] (unknowns invalidKnown)+    assertEqual 1 (length invalidKnown)+    for_ [PermissiveConformance, StrictAuthoring] $ \mode -> do+      active <- validate mode conditionalSpec [("type", String "Note"), ("value", shapeValue shape (record ["note"]))]+      -- Unknown checking does not manufacture keys or replace missing presence.+      assertEqual [] (unknowns active)+      model <- validate mode conditionalSpec [("type", String "Note"), ("value", shapeValue shape (object ["kind" .= ("model" :: Text), "provider" .= ("openai" :: Text), "stray" .= Null]))]+      assertEqual (violationsFor shape "stray") (unknowns model)+      assertEqual (if mode == StrictAuthoring then 2 else 1) (length model)+    let invalidOptional = conditionalRules & #optional .~ [(scalar "note") & #when .~ Just conditional]+    case compileProfile (mkSpec shape invalidOptional) of+      Right _ -> Left "closure allowed an optional condition"+      Left errs -> assertBool "expected OptionalFieldWithCondition" (any (\case OptionalFieldWithCondition {} -> True; _ -> False) errs)+    -- A false parent condition changes only presence; supplied children stay closed.+    let gate = (requiredField "mode") & #cardinality .~ Scalar & #allowedValues .~ ["on", "off"]+        falseParent = (mkParent shape (rules False [])) & #when .~ Just (FieldCondition "mode" ["on"])+        gated = (specFor Nothing Nothing) & #frontmatter .~ (emptyTestFrontmatterRules & #required .~ [falseParent] & #optional .~ [gate])+    gatedViolations <- validate PermissiveConformance gated [("mode", String "off"), ("value", shapeValue shape (record ["stray"]))]+    assertEqual (violationsFor shape "stray") (unknowns gatedViolations)+  -- Separate policies for two fields and both accepted shapes of one field.+  for_ [(a, b) | a <- [False, True], b <- [False, True]] $ \(elementOpen, objectOpen) -> do+    let elementRules = rules elementOpen ["name"]+        objects = rules objectOpen ["name"]+        dual = specFor (Just elementRules) (Just objects)+        separate = dual & #frontmatter .~ (emptyTestFrontmatterRules & #optional .~ [parent (Just elementRules) Nothing, (parent Nothing (Just objects)) & #field .~ "settings"])+    compiled <- firstShow (compileProfile dual)+    effective <- lookupCompiledRule "value" (compiledProfileBaseRules compiled)+    assertEqual (Just elementOpen) (fieldRuleElementAllowsUnknownFields effective)+    assertEqual (Just objectOpen) (fieldRuleObjectAllowsUnknownFields effective)+    for_ [(True, elementOpen), (False, objectOpen)] $ \(shape, open) -> do+      actual <- check dual (shapeValue shape (record ["name", "stray"]))+      assertEqual (if open then [] else violationsFor shape "stray") (unknowns actual)+    combined <- validate PermissiveConformance separate [("value", array [record ["stray"]]), ("settings", record ["stray"])]+    assertEqual ((if elementOpen then 0 else 1) + (if objectOpen then 0 else 1)) (length (unknowns combined))+  -- Sorting is per record, indices are stable, null is still a key, Unicode survives.+  let closed = specFor (Just (rules False ["name"])) Nothing+      mixed = array [object ["z" .= Null, "a" .= ("" :: Text), "名前" .= ([] :: [Text])], record ["again"], Number 1]+  mixedViolations <- check closed mixed+  assertEqual+    [NestedFieldNotInProfile cid (path [ArrayIndex 0, FieldName key]) | key <- ["a", "z", "名前"]]+    (take 3 mixedViolations)+  assertEqual [NestedFieldNotInProfile cid (path [ArrayIndex 1, FieldName "again"]), NestedElementNotRecord cid (path [ArrayIndex 2]) (Number 1)] (drop 3 mixedViolations)+  -- Closure and predecessor constraints coexist after scope merging.+  let constrained =+        (rules False ["trigger", "required", "start", "end"])+          & #optional+          .~ [scalar "trigger", scalar "required", (scalar "start") & #format .~ Just Rfc3339Utc, (scalar "end") & #format .~ Just Rfc3339Utc]+          & #presenceConstraints+          .~ [PresenceConstraint Nothing [ValueSelector "trigger" Nothing] [ValueSelector "required" Nothing] []]+          & #timestampOrderConstraints+          .~ [TimestampOrderConstraint "start" "end"]+      spec = typed (specFor (Just constrained) Nothing) (parent (Just (rules True ["typed"])) Nothing)+  coexist <- check spec (array [object ["trigger" .= True, "start" .= ("2026-10-02T00:00:00Z" :: Text), "end" .= ("2026-10-01T00:00:00Z" :: Text), "stray" .= Null]])+  assertEqual (violationsFor True "stray") (unknowns coexist)+  assertEqual 1 (length [() | ConstraintPresenceMissing {} <- coexist])+  assertEqual 1 (length [() | TimestampOrderViolation {} <- coexist])++-- Load-bearing sweeps ---------------------------------------------------------++-- | A renderer that needs nothing from the CLI: 'show' names the field, which is+-- all the legacy predicate looks for.+showRender :: Sweep.Render+showRender _ _ violation = Text.pack (show violation)++loadSweepFixture :: IO (ProfileSpec, CompiledProfile, Sweep.Suite)+loadSweepFixture = do+  profilePath <- fixtureFilePath "sweep/profile.dhall"+  acceptPath <- fixturePath "sweep/accept"+  casesPath <- fixturePath "sweep/cases"+  spec <- either (fail . Text.unpack) pure =<< loadProfileFile profilePath+  compiled <- either (fail . show) pure (compileProfile spec)+  suite <- either (fail . show) pure =<< Sweep.loadSuite [acceptPath] casesPath+  pure (spec, compiled, suite)++testSweepEnumeration :: IO (Either Text ())+testSweepEnumeration = do+  (spec, _, _) <- loadSweepFixture+  nestedPath <- fixtureFilePath "profiles/nested-references-and-uniqueness.dhall"+  nestedSpec <- either (fail . Text.unpack) pure =<< loadProfileFile nestedPath+  pure $ do+    assertEqual+      [ "profile/required/type#delete",+        "profile/required/title#delete",+        "type:Note/required/status#delete",+        "type:Note/required/status#allowedValues",+        "type:Note/optional/summary#delete"+      ]+      (map Sweep.relaxationId (Sweep.enumerateRelaxations Sweep.LegacyKinds spec))+    assertEqual+      [ "profile/required/type#delete",+        "profile/required/type#presence",+        "profile/required/title#delete",+        "profile/required/title#presence",+        "type:Note/required/status#delete",+        "type:Note/required/status#presence",+        "type:Note/required/status#allowedValues",+        "type:Note/optional/summary#delete"+      ]+      (map Sweep.relaxationId (Sweep.enumerateRelaxations Sweep.DefaultKinds spec))+    assertEqual+      [ "profile/required/type#delete",+        "profile/required/requestId#delete",+        "profile/required/requestId#format",+        "profile/required/dependencies#delete",+        "profile/required/dependencies/elementFields/required/ref#delete",+        "profile/required/dependencies/elementFields/required/ref#allowSelf",+        "profile/required/dependencies/elementFields/required/ref#allowLocal",+        "profile/required/dependencies/elementFields/required/ref#externalUriPattern",+        "profile/required/acceptanceCriteria#delete",+        "profile/required/acceptanceCriteria#uniqueBy",+        "profile/required/acceptanceCriteria/elementFields/required/id#delete",+        "profile/required/acceptanceCriteria/elementFields/required/id#format",+        "profile/required/acceptanceCriteria/elementFields/required/text#delete"+      ]+      (map Sweep.relaxationId (Sweep.enumerateRelaxations Sweep.LegacyKinds nestedSpec))+    assertEqual+      (Just "id")+      (listToMaybe [Sweep.relaxationField r | r <- Sweep.enumerateRelaxations Sweep.LegacyKinds nestedSpec, Sweep.relaxationId r == "profile/required/acceptanceCriteria/elementFields/required/id#format"])++testSweepApplyRelaxation :: IO (Either Text ())+testSweepApplyRelaxation = do+  (spec, _, _) <- loadSweepFixture+  nestedPath <- fixtureFilePath "profiles/nested-references-and-uniqueness.dhall"+  nestedSpec <- either (fail . Text.unpack) pure =<< loadProfileFile nestedPath+  let status = Sweep.RuleTarget (Sweep.RuleLocation (Sweep.TypeScope "Note") Sweep.RequiredList "status" Nothing)+      note relaxed = case relaxed ^. #types of+        [rule] -> Right (rule ^. #frontmatter)+        other -> Left ("expected one type rule, got " <> Text.pack (show (length other)))+      relax target kind = Sweep.applyRelaxation (Sweep.Relaxation target kind)+      fieldsOf = map (^. #field)+      ref = Sweep.RuleTarget (Sweep.RuleLocation Sweep.ProfileScope Sweep.RequiredList "dependencies" (Just (Sweep.ElementFields, Sweep.RequiredList, "ref")))+      nestedRef relaxed = do+        dependencies <- lookupRawRule "dependencies" (relaxed ^. #frontmatter . #required)+        case dependencies ^. #elementFields of+          Just nestedRules | [member] <- nestedRules ^. #required -> Right member+          _ -> Left "expected one nested rule under dependencies"+  pure $ do+    deleted <- note (relax status Sweep.Delete spec)+    assertEqual [] (fieldsOf (deleted ^. #required))+    demoted <- note (relax status Sweep.Presence spec)+    assertEqual [] (fieldsOf (demoted ^. #required))+    assertEqual ["summary", "status"] (fieldsOf (demoted ^. #optional))+    cleared <- note (relax status Sweep.ClearVocabulary spec)+    assertEqual [[]] (map (^. #allowedValues) (cleared ^. #required))+    admitted <- note (relax status (Sweep.AdmitValue "wip") spec)+    assertEqual [["draft", "final", "wip"]] (map (^. #allowedValues) (admitted ^. #required))+    anyShape <- note (relax status Sweep.DropCardinality spec)+    assertEqual [Any] (map (^. #cardinality) (anyShape ^. #required))+    assertEqual spec (relax (Sweep.RuleTarget (Sweep.RuleLocation (Sweep.TypeScope "Missing") Sweep.RequiredList "status" Nothing)) Sweep.Delete spec)+    selfAllowed <- nestedRef (relax ref Sweep.AllowSelf nestedSpec)+    assertEqual (Just True) ((^. #allowSelf) <$> selfAllowed ^. #reference)+    localAllowed <- nestedRef (relax ref Sweep.AllowLocal nestedSpec)+    assertEqual (Just True) ((^. #allowLocal) <$> localAllowed ^. #reference)+    unpatterned <- nestedRef (relax ref Sweep.DropExternalUriPattern nestedSpec)+    assertEqual (Just Nothing) ((^. #externalUriPattern) <$> unpatterned ^. #reference)+    unreferenced <- nestedRef (relax ref Sweep.DropReference nestedSpec)+    assertEqual Nothing (unreferenced ^. #reference)+    let criteria = Sweep.RuleTarget (Sweep.RuleLocation Sweep.ProfileScope Sweep.RequiredList "acceptanceCriteria" Nothing)+    notUnique <- lookupRawRule "acceptanceCriteria" (relax criteria Sweep.DropUniqueBy nestedSpec ^. #frontmatter . #required)+    assertEqual Nothing (notUnique ^. #uniqueBy)+    flat <- lookupRawRule "acceptanceCriteria" (relax criteria (Sweep.DropNested Sweep.ElementFields) nestedSpec ^. #frontmatter . #required)+    assertBool "elementFields dropped" (isNothing (flat ^. #elementFields))++testSweepExpectationOrder :: Either Text ()+testSweepExpectationOrder = do+  parsed <-+    Sweep.parseExpectations+      "{\"zeta\": \"status\", \"alpha\": {\"field\": \"docId\", \"diagnostics\": 2}, \"mid\": \"title\"}"+  assertEqual+    [ ("zeta", Sweep.CaseExpectation "status" 1),+      ("alpha", Sweep.CaseExpectation "docId" 2),+      ("mid", Sweep.CaseExpectation "title" 1)+    ]+    parsed+  assertBool "a non-object is rejected" (either (const True) (const False) (Sweep.parseExpectations "[]"))+  assertBool "a malformed entry is rejected" (either (const True) (const False) (Sweep.parseExpectations "{\"a\": 3}"))++testSweepWitnesses :: IO (Either Text ())+testSweepWitnesses = do+  (_, compiled, suite) <- loadSweepFixture+  pure $ do+    assertEqual ["note-missing-title", "note-bad-status"] (map (^. #name) (suite ^. #cases))+    prepared <- first (Text.pack . show) (Sweep.checkBaseline showRender compiled suite)+    let results = Sweep.sweepProfile [] prepared (Sweep.planRelaxations Sweep.LegacyKinds prepared)+        outcomes = [(Sweep.relaxationId (r ^. #relaxation), Sweep.legacyOutcome (r ^. #observation)) | r <- results]+    assertEqual+      [ ("profile/required/type#delete", "UNPROTECTED"),+        ("profile/required/title#delete", "fixture note-missing-title"),+        ("type:Note/required/status#delete", "fixture note-bad-status"),+        ("type:Note/required/status#allowedValues", "fixture note-bad-status"),+        ("type:Note/optional/summary#delete", "UNPROTECTED")+      ]+      outcomes++testSweepBaselineFault :: IO (Either Text ())+testSweepBaselineFault = do+  (_, compiled, suite) <- loadSweepFixture+  let misdirected =+        suite+          & #cases+          . traverse+          . filtered ((== "note-bad-status") . (^. #name))+          . #expectation+          . #field+          .~ "title"+  pure $ case Sweep.checkBaseline showRender compiled misdirected of+    Left (Sweep.CaseExpectationUnmet "note-bad-status" (Sweep.CaseExpectation "title" 1) [_] :| []) -> Right ()+    Left faults -> Left ("unexpected faults: " <> Text.pack (show faults))+    Right _ -> Left "a case whose expected field is wrong must fail the baseline"++lookupRawRule :: Text -> [FieldRule] -> Either Text FieldRule+lookupRawRule key rules =+  case [rule | rule <- rules, rule ^. #field == key] of+    [rule] -> Right rule+    _ -> Left ("expected one raw rule for " <> key)++sweepLogFile :: LogFile+sweepLogFile = LogFile "log.md" (parseLog "# Bundle Update Log\n\n## 2026-10-28\n* **Add**: Created the sweep fixture.\n")++sweepDocument :: [(Text, Text)] -> Text+sweepDocument fields =+  "---\n" <> Text.unlines [key <> ": " <> value | (key, value) <- fields] <> "---\n\n# Sweep fixture\n\nA concept.\n"++-- | A bundle held in memory, with one fresh log so strict acceptance passes.+memoryBundle :: FilePath -> [(Text, [(Text, Text)])] -> Either Text Sweep.SuiteBundle+memoryBundle bundlePath documents = do+  concepts <- for documents $ \(rawId, fields) -> do+    conceptId <- parseTestConceptId rawId+    document <- firstShow (parseDocument (sweepDocument fields))+    pure (conceptFromDocument conceptId document)+  pure (Sweep.SuiteBundle bundlePath concepts (bundleInventoryOfConcepts concepts) VersionUndeclared [sweepLogFile])++memoryCase :: Text -> Text -> [(Text, Text)] -> Either Text Sweep.RejectionCase+memoryCase caseName expected fields =+  Sweep.RejectionCase caseName (Sweep.CaseExpectation expected 1) <$> memoryBundle (Text.unpack caseName) [("tasks/" <> caseName, fields)]++setSweepField :: Text -> Text -> [(Text, Text)] -> [(Text, Text)]+setSweepField key value fields = [(k, v) | (k, v) <- fields, k /= key] <> [(key, value)]++baseTask :: [(Text, Text)]+baseTask =+  [ ("type", "Task"),+    ("title", "A task"),+    ("description", "A task in the sweep fixture."),+    ("timestamp", "\"2026-10-01T00:00:00Z\""),+    ("docId", "TASK-1"),+    ("status", "open")+  ]++loadCompiledFixture :: FilePath -> IO (ProfileSpec, CompiledProfile)+loadCompiledFixture name = do+  path <- fixtureFilePath name+  spec <- either (fail . Text.unpack) pure =<< loadProfileFile path+  compiled <- either (fail . show) pure (compileProfile spec)+  pure (spec, compiled)++-- | The classification fixture's suite: one accepted task and three cases, each+-- breaking exactly one rule.+classificationSuite :: Either Text Sweep.Suite+classificationSuite = do+  accept <- memoryBundle "accept" [("tasks/first", baseTask <> [("parent", "https://example.com/tasks/1")])]+  cases <-+    sequence+      [ memoryCase "task-bad-status" "status" (setSweepField "status" "wip" baseTask),+        memoryCase "task-local-parent" "parent" (baseTask <> [("parent", "TASK-9")]),+        memoryCase "task-missing-closedby" "closedBy" (setSweepField "status" "done" baseTask)+      ]+  pure (Sweep.Suite [accept] cases)++sweepOutcomes :: [Sweep.SweepException] -> Sweep.KindSet -> Sweep.PreparedSuite -> [(Text, Sweep.SweepResult)]+sweepOutcomes exceptions kinds prepared =+  [(Sweep.relaxationId (result ^. #relaxation), result) | result <- Sweep.sweepProfile exceptions prepared (Sweep.planRelaxations kinds prepared)]++expectOutcome :: [(Text, Sweep.SweepResult)] -> Text -> Sweep.Outcome -> Either Text ()+expectOutcome results relaxation expected =+  case lookup relaxation results of+    Nothing -> Left ("no result for " <> relaxation <> " among " <> Text.pack (show (map fst results)))+    Just result+      | result ^. #outcome == expected -> Right ()+      | otherwise -> Left (relaxation <> ": expected " <> Text.pack (show expected) <> ", got " <> Text.pack (show (result ^. #outcome)) <> " from " <> Text.pack (show (result ^. #observation)))++testSweepClassification :: IO (Either Text ())+testSweepClassification = do+  (_, compiled) <- loadCompiledFixture "sweep/classification.dhall"+  pure $ do+    suite <- classificationSuite+    prepared <- first (Text.pack . show) (Sweep.checkBaseline showRender compiled suite)+    let results = sweepOutcomes [] Sweep.DefaultKinds prepared+        expect = expectOutcome results+    -- A vocabulary a condition depends on cannot be cleared, so admitting the+    -- value a case reports stands in for it.+    expect "type:Task/required/status#admitValue:wip" Sweep.Protected+    expect "type:Task/required/status#allowedValues" (Sweep.Covered "type:Task/required/status#admitValue:wip" "task-bad-status")+    expect "type:Task/required/status#delete" Sweep.DescriptorInvalidOutcome+    expect "type:Task/required/status#presence" Sweep.Unprotected+    expect "type:Task/required/closedBy#delete" Sweep.Protected+    expect "type:Task/required/closedBy#presence" Sweep.Protected+    -- allowLocal turns the local-handle rejection into a dangling-handle one on+    -- the same field, which the legacy predicate cannot tell apart.+    expect "type:Task/optional/parent#allowLocal" (Sweep.Covered "type:Task/optional/parent#reference" "task-local-parent")+    assertEqual (Just ["task-local-parent"]) ((^. #observation . #facetWitnesses) <$> lookup "type:Task/optional/parent#allowLocal" results)+    expect "type:Task/optional/parent#allowSelf" (Sweep.Inert "allowSelf is never read while allowLocal is False")+    expect "type:Task/optional/note#delete" (Sweep.Inert "the relaxed profile compiles to the same behaviour key as the baseline")+    expect "type:Task/optional/priority#allowedValues" Sweep.Unprotected+    assertBool "a composite unit is not reported as its own result" (isNothing (lookup "type:Task/optional/parent#reference" results))+    assertBool "no protected result lacks a witness" (and [not (null (r ^. #observation . #witnesses)) | (_, r) <- results, r ^. #outcome == Sweep.Protected])++testSweepClosedProfile :: IO (Either Text ())+testSweepClosedProfile = do+  (_, compiled) <- loadCompiledFixture "sweep/closed.dhall"+  pure $ do+    let item extra =+          [("type", "Item"), ("title", "An item"), ("description", "An item."), ("timestamp", "\"2026-10-01T00:00:00Z\"")] <> extra+    accept <- memoryBundle "accept" [("items/first", item [("size", "s"), ("colour", "red")])]+    badSize <- memoryCase "item-bad-size" "size" (item [("size", "xl")])+    prepared <- first (Text.pack . show) (Sweep.checkBaseline showRender compiled (Sweep.Suite [accept] [badSize]))+    let results = sweepOutcomes [] Sweep.LegacyKinds prepared+        expect = expectOutcome results+    expect "profile/optional/size#allowedValues" Sweep.Protected+    expect "profile/optional/size#delete" (Sweep.Subsumed ["profile/optional/size#allowedValues"])+    expect "profile/optional/colour#allowedValues" Sweep.Unprotected+    expect "profile/optional/colour#delete" Sweep.AcceptanceObservableOutcome+    assertEqual (Just "acceptance-fails") (Sweep.legacyOutcome . (^. #observation) <$> lookup "profile/optional/size#delete" results)++testSweepContradiction :: IO (Either Text ())+testSweepContradiction = do+  (_, compiled) <- loadCompiledFixture "sweep/classification.dhall"+  pure $ do+    suite <- classificationSuite+    prepared <- first (Text.pack . show) (Sweep.checkBaseline showRender compiled suite)+    -- A key that erases everything claims every relaxation is inert.+    let erasesEverything = Sweep.withBehaviourKey (const (Sweep.behaviourKey compiled)) prepared+        results = sweepOutcomes [] Sweep.DefaultKinds erasesEverything+    expectOutcome results "type:Task/required/closedBy#delete" Sweep.Contradiction++testSweepExceptions :: IO (Either Text ())+testSweepExceptions = do+  (_, compiled) <- loadCompiledFixture "sweep/classification.dhall"+  pure $ do+    suite <- classificationSuite+    prepared <- first (Text.pack . show) (Sweep.checkBaseline showRender compiled suite)+    let shared = Sweep.SweepException "type:Task/optional/priority#allowedValues" (Sweep.SharedFamily "tasks") "Tested in the tasks family."+        inexpressible = Sweep.SweepException "type:Task/required/status#delete" (Sweep.OverlappingRule "type:Task/required/closedBy") "closedBy's condition needs status."+        notAGap = Sweep.SweepException "type:Task/required/closedBy#delete" (Sweep.Deferred "mori://shinzui/okf/okf/improvement-requests/concepts/IR-12") "Protected after all."+        absent = Sweep.SweepException "type:Task/optional/ghost#delete" (Sweep.SharedFamily "tasks") "No such rule."+        exceptions = [shared, inexpressible, notAGap, absent]+        results = sweepOutcomes exceptions Sweep.DefaultKinds prepared+        outcomes = [(identifier, result ^. #outcome) | (identifier, result) <- results]+    expectOutcome results "type:Task/optional/priority#allowedValues" (Sweep.ExceptionOutcome shared)+    expectOutcome results "type:Task/required/status#delete" (Sweep.ExceptionOutcome inexpressible)+    expectOutcome results "type:Task/required/closedBy#delete" Sweep.Protected+    assertEqual [notAGap, absent] (Sweep.staleExceptions Sweep.DefaultKinds False exceptions outcomes)+    assertEqual [notAGap] (Sweep.staleExceptions Sweep.DefaultKinds True exceptions outcomes)+    -- A presence exception names a kind a legacy run never enumerates.+    let presence = Sweep.SweepException "type:Task/required/ghost#presence" (Sweep.SharedFamily "tasks") "Default kinds only."+    assertEqual [] (Sweep.staleExceptions Sweep.LegacyKinds False [presence] outcomes)++testSweepMalformedExceptions :: Either Text ()+testSweepMalformedExceptions = do+  let rejected bytes = either (const True) (const False) (Sweep.parseExceptions bytes)+      entry fields = "{\"version\": 1, \"exceptions\": [{" <> fields <> "}]}"+  parsed <- Sweep.parseExceptions (entry "\"relaxation\": \"profile/required/x#delete\", \"class\": \"shared-family\", \"home\": \"okfV02\", \"rationale\": \"Spliced.\"")+  assertEqual [Sweep.SweepException "profile/required/x#delete" (Sweep.SharedFamily "okfV02") "Spliced."] parsed+  assertBool "version 2 is rejected" (rejected "{\"version\": 2, \"exceptions\": []}")+  assertBool "an unknown class is rejected" (rejected (entry "\"relaxation\": \"r\", \"class\": \"vibes\", \"rationale\": \"x\""))+  assertBool "shared-family needs home" (rejected (entry "\"relaxation\": \"r\", \"class\": \"shared-family\", \"rationale\": \"x\""))+  assertBool "overlapping-rule needs overlapsWith" (rejected (entry "\"relaxation\": \"r\", \"class\": \"overlapping-rule\", \"rationale\": \"x\""))+  assertBool "deferred needs a mori:// request" (rejected (entry "\"relaxation\": \"r\", \"class\": \"deferred\", \"request\": \"IR-3\", \"rationale\": \"x\""))+  assertBool "an empty rationale is rejected" (rejected (entry "\"relaxation\": \"r\", \"class\": \"shared-family\", \"home\": \"h\", \"rationale\": \" \""))++-- | Each erasure must leave the key equal and, on concepts that exercise the+-- erased member, the violations identical; a description on a rule with a+-- presence clause must not be erased.+testSweepBehaviourKeyErasures :: IO (Either Text ())+testSweepBehaviourKeyErasures = do+  (spec, compiled) <- loadCompiledFixture "sweep/classification.dhall"+  pure $ do+    probes <-+      traverse+        (\(rawId, fields) -> conceptFromDocument <$> parseTestConceptId rawId <*> firstShow (parseDocument (sweepDocument fields)))+        [ ("tasks/a", baseTask <> [("note", "anything"), ("parent", "TASK-1")]),+          ("tasks/b", setSweepField "docId" "TASK-2" baseTask <> [("parent", "https://example.com/tasks/1")]),+          ("tasks/c", setSweepField "docId" "TASK-3" baseTask <> [("parent", "TASK-2"), ("note", "[1, 2]")]),+          ("tasks/d", [(k, v) | (k, v) <- setSweepField "docId" "TASK-4" baseTask, k /= "title"])+        ]+    let onType f = spec & #types . traverse . #frontmatter %~ f+        onRule name f = onType (\rules -> rules & #optional . traverse . filtered ((== name) . (^. #field)) %~ f)+        withReference f = onRule "parent" (\rule -> rule & #reference . _Just %~ f)+        same label relaxed = do+          relaxedCompiled <- first (\errors -> label <> ": " <> Text.pack (show errors)) (compileProfile relaxed)+          assertBool (label <> ": behaviour key differs") (Sweep.behaviourKey relaxedCompiled == Sweep.behaviourKey compiled)+          for_ [PermissiveConformance, StrictAuthoring] $ \mode ->+            assertEqual (validateProfile mode compiled probes) (validateProfile mode relaxedCompiled probes)+        unpatterned = withReference (\policy -> policy & #externalUriSchemes .~ [] & #externalUriPattern .~ Nothing)+        patterned = withReference (\policy -> policy & #externalUriSchemes .~ [] & #externalUriPattern ?~ "https://example[.]com/.*")+    same "unconstrained optional rule in an open record" (onType (#optional %~ filter ((/= "note") . (^. #field))))+    same "description on a rule without a presence clause" (onRule "note" (#description .~ Nothing))+    same "allowSelf while allowLocal is False" (withReference (#allowSelf .~ True))+    unpatternedCompiled <- first (Text.pack . show) (compileProfile unpatterned)+    patternedCompiled <- first (Text.pack . show) (compileProfile patterned)+    assertBool "externalUriPattern without schemes is erased" (Sweep.behaviourKey unpatternedCompiled == Sweep.behaviourKey patternedCompiled)+    for_ [PermissiveConformance, StrictAuthoring] $ \mode ->+      assertEqual (validateProfile mode unpatternedCompiled probes) (validateProfile mode patternedCompiled probes)+    let describedTitle = spec & #frontmatter . #required . traverse . filtered ((== "title") . (^. #field)) . #description ?~ "Shown when title is missing."+    describedCompiled <- first (Text.pack . show) (compileProfile describedTitle)+    assertBool "a required rule's description is kept" (Sweep.behaviourKey describedCompiled /= Sweep.behaviourKey compiled)
+ test/fixtures/catalogue/Profile/Hypothesis.dhall view
@@ -0,0 +1,43 @@+--| A falsifiable hypothesis shared by coordinated campaigns and initiatives.+let okf = ./okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let Cardinality = okf.Cardinality++in  FieldRule::{+    , field = "hypothesis"+    , description = Some+        "The problem, belief, prediction, and falsification condition."+    , cardinality = Cardinality.Any+    , objectFields = Some NestedRules::{+      , required =+        [ NestedFieldRule::{+          , field = "problem"+          , description = Some "The observed problem being addressed."+          , cardinality = Cardinality.Scalar+          }+        , NestedFieldRule::{+          , field = "belief"+          , description = Some "The causal belief being tested."+          , cardinality = Cardinality.Scalar+          }+        , NestedFieldRule::{+          , field = "prediction"+          , description = Some+              "The observable result expected if the belief holds."+          , cardinality = Cardinality.Scalar+          }+        , NestedFieldRule::{+          , field = "falsifiedIf"+          , description = Some "The observation that would falsify the belief."+          , cardinality = Cardinality.Scalar+          }+        ]+      , optional = [] : List NestedFieldRule.Type+      }+    }
test/fixtures/catalogue/Profile/V02.dhall view
@@ -32,13 +32,19 @@ -- ## Policy one: where the house `status` key collides, the house key wins -- -- OKF v0.2 §5.4 gives `status` the vocabulary `draft` / `stable` / `deprecated`.--- Seven profiles in this repository use the same key name for a house lifecycle--- vocabulary — five that predate v0.2, and two introduced after it that answer a--- question v0.2's vocabulary cannot:+-- Nineteen profiles in this repository use the same key name for a house lifecycle+-- vocabulary — five that predate v0.2, and fourteen introduced after it that answer+-- a question v0.2's vocabulary cannot: -- --   * `documentation.architectureDecisions` — `Accepted`, and siblings --   * `documentation.patternCatalog`        — `current`, `deprecated`+--   * `documentation.productResearch`       — study `planned`, `active`,+--                                             `complete`, `cancelled`; finding+--                                             `current`, `superseded`, `withdrawn` --   * `documentation.researchDocuments`     — `active`, `complete`, `superseded`+--   * `documentation.specifications`        — `draft`, `proposed`, `ratified`,+--                                             `superseded`, `withdrawn`+--   * `documentation.terminology`           — `current`, `deprecated` --   * `coordination.improvementRequests`    — `proposed`, `accepted`, `in-progress`, --                                             `completed`, `rejected`, `withdrawn`, --                                             `superseded`@@ -48,8 +54,32 @@ --   * `coordination.bugReports`             — `reported`, `confirmed`, `in-progress`, --                                             `fixed`, `wont-fix`, `duplicate`, --                                             `not-a-bug`, `cannot-reproduce`+--   * `coordination.jobs`                   — `draft`, `active`, `retired`, plus a+--                                             second house key, `validationStatus`:+--                                             `untested`, `supported`, `mixed`,+--                                             `challenged`+--   * `coordination.features`               — `discovered`, `planned`, `in-progress`,+--                                             `delivered`, `blocked`, `deferred`,+--                                             `retired`+--   * `coordination.designs`                — brief and breadboard `draft`,+--                                             `validated`, `retired`; detailed+--                                             design `exploring`, `chosen`,+--                                             `designed`, `retired`+--   * `coordination.frictionLog`            — `logged`, `promoted`, `resolved`,+--                                             `accepted`, `duplicate` ----- Those seven keep their house vocabulary and do **not** splice in `status` or+--   * `coordination.campaigns`              — campaign and email lifecycles+--   * `coordination.audiences`              — segment/persona lifecycles and+--                                             persona validationStatus+--+--   * `coordination.strategy`               — theme, objective and initiative lifecycles+--   * `coordination.launches`               — launch and page publication lifecycles+--   * `documentation.messaging`             — positioning and message lifecycles+--+-- `assurance.claimChecks` uses its house verdict as a complete result+-- vocabulary, taking neither status nor staleAfter (ADR-21).+--+-- Those nineteen keep their house vocabulary and do **not** splice in `status` or -- `staleAfter` from this module. This is sanctioned rather than tolerated: a -- profile key name does not imply the OKF core key of that name, and okf never -- rejects a profile over it. What okf checks instead is value *formats*, because
test/fixtures/catalogue/Profile/okf.dhall view
@@ -1808,6 +1808,7 @@               , when : Optional { field : Text, hasValue : List Text }               }         }+    , guidance : Optional Text     , idField : Optional Text     , name : Text     , okfVersion : Text@@ -2582,6 +2583,7 @@                     , when : Optional { field : Text, hasValue : List Text }                     }               }+          , guidance : Optional Text           , idPrefix : Optional Text           , pathPattern : Optional Text           , requireSchemaSection : Bool@@ -3338,6 +3340,7 @@               , when : Optional { field : Text, hasValue : List Text }               }         }+    , guidance : Optional Text     , idPrefix : Optional Text     , pathPattern : Optional Text     , requireSchemaSection : Bool@@ -6345,6 +6348,7 @@                   , when : Optional { field : Text, hasValue : List Text }                   }             }+        , guidance : Optional Text         , idField : Optional Text         , name : Text         , okfVersion : Text@@ -7125,6 +7129,7 @@                         , when : Optional { field : Text, hasValue : List Text }                         }                   }+              , guidance : Optional Text               , idPrefix : Optional Text               , pathPattern : Optional Text               , requireSchemaSection : Bool@@ -7904,6 +7909,7 @@                    , when : Optional { field : Text, hasValue : List Text }                    }         }+      , guidance = None Text       , idField = None Text       , okfVersion = "0.1"       , requireBundleVersion = None Text@@ -8740,6 +8746,7 @@                                Optional { field : Text, hasValue : List Text }                            }                      }+                 , guidance : Optional Text                  , idPrefix : Optional Text                  , pathPattern : Optional Text                  , requireSchemaSection : Bool@@ -9519,6 +9526,7 @@                   , when : Optional { field : Text, hasValue : List Text }                   }             }+        , guidance : Optional Text         , idPrefix : Optional Text         , pathPattern : Optional Text         , requireSchemaSection : Bool@@ -10295,6 +10303,7 @@                    , when : Optional { field : Text, hasValue : List Text }                    }         }+      , guidance = None Text       , idPrefix = None Text       , pathPattern = None Text       , requireSchemaSection = False
test/fixtures/catalogue/package.dhall view
@@ -1,4 +1,4 @@---| Offline snapshot of mori://shinzui/okf-profiles at v0.14.0.+--| Offline snapshot of mori://shinzui/okf-profiles at v0.25.0. -- Generated by scripts/refresh-default-registry.sh; do not edit by hand. -- Profile/okf.dhall is the resolved schema pinned by that release, so this -- fixture evaluates without network access.@@ -8,12 +8,12 @@ -- ready-made profiles. With a versioned, hash-pinned remote import: -- --     let okf =---           https://raw.githubusercontent.com/shinzui/okf-profiles/v0.1.0/package.dhall---             sha256:0000000000000000000000000000000000000000000000000000000000000000+--           https://raw.githubusercontent.com/shinzui/okf-profiles/v0.25.0/package.dhall+--             sha256:ec74cc6f7b8ee1a5af81ee7fc8804f35cf2c9ba4010671d9e881da72eb6719d3 -- --     in  okf.postgresql // { name = "acme-warehouse" } ----- See README.md for how to generate the real hash (`dhall freeze`) and for the+-- v0.25.0 requires okf 0.9.0.0 or later. See README.md for how to generate the real hash (`dhall freeze`) and for the -- public-repo / pinning rationale. let okf = ./Profile/okf.dhall @@ -30,6 +30,7 @@     , FieldFormat = okf.FieldFormat     , mk = okf.mk     , reviewRule = ./Profile/ReviewRule.dhall+    , hypothesis = ./Profile/Hypothesis.dhall     , modelReview = ./Profile/ModelReview.dhall     , v02 = ./Profile/V02.dhall     , assurance = ./profiles/assurance/package.dhall
+ test/fixtures/catalogue/profiles/assurance/claim-checks.dhall view
@@ -0,0 +1,183 @@+--| A Claim Check is assurance: it records that wording was tested against data.+-- It differs from verificationEvidence (software runs) and product-research Findings+-- (customer observations). measured is evidence for copy, not a job-outcome measure.+-- verdict is the house result vocabulary; this result record deliberately takes+-- neither OKF status nor staleAfter, as event assurance already does (ADR-15).+-- No recommended fields and no legacyTimestamp: unchecked drafts have no evidence,+-- and the shared type starts at v0.2. Foreign concept references are canonical;+-- query/computation alternatives and target types belong to check-gtm.py.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++let externalOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "CLM"+          , allowLocal = False+          , externalUriSchemes = [ "mori" ]+          , externalUriPattern = Some (conceptUri prefix)+          }++in  Profile::{+    , name = "claim-checks"+    , description = Some+        "Claim Checks record what wording was checked, by whom, against what evidence, and the result."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "claimId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ FieldRule::{+          , field = "type"+          , description = Some "The declared concept type."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "title"+          , description = Some "Human-readable concept title."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "description"+          , description = Some "One sentence describing the concept."+          , cardinality = Cardinality.Scalar+          }+        , v02.generated+        ]+      , optional =+        [ FieldRule::{+          , field = "tags"+          , description = Some "Producer-defined search and grouping tags."+          , cardinality = Cardinality.List+          }+        , reviewRule+        , v02.verified+        , v02.sources+        ]+      }+    , types =+      [ TypeRule::{+        , type = "Claim Check"+        , description = Some+            "Evidence that a specific statement was checked against data."+        , idPrefix = Some "CLM"+        , pathPattern = Some "**"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "claimId"+              , description = Some "Bundle-scoped stable CLM-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "CLM")+              }+            , FieldRule::{+              , field = "statement"+              , description = Some "Exact wording that was checked."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "usedIn"+              , description = Some+                  "Canonical concept URIs or repository paths where the statement is used."+              , cardinality = Cardinality.List+              }+            , FieldRule::{+              , field = "verdict"+              , description = Some+                  "Result of comparing the statement with evidence."+              , cardinality = Cardinality.Scalar+              , allowedValues =+                [ "unchecked", "match", "close", "wrong", "cannot-verify" ]+              }+            , FieldRule::{+              , field = "checkedBy"+              , description = Some "Actor who performed the check."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Actor+              , when = Some+                { field = "verdict"+                , hasValue = [ "match", "close", "wrong", "cannot-verify" ]+                }+              }+            , FieldRule::{+              , field = "measured"+              , description = Some "What the evidence actually establishes."+              , cardinality = Cardinality.Scalar+              , when = Some+                { field = "verdict", hasValue = [ "match", "close", "wrong" ] }+              }+            , FieldRule::{+              , field = "asOf"+              , description = Some "UTC time the measurement describes."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Rfc3339Utc+              , when = Some+                { field = "verdict", hasValue = [ "match", "close", "wrong" ] }+              }+            , FieldRule::{+              , field = "suggestedWording"+              , description = Some "Accurate replacement wording."+              , cardinality = Cardinality.Scalar+              , when = Some+                { field = "verdict", hasValue = [ "close", "wrong" ] }+              }+            , FieldRule::{+              , field = "unverifiableBecause"+              , description = Some "Why this statement cannot be verified."+              , cardinality = Cardinality.Scalar+              , when = Some+                { field = "verdict", hasValue = [ "cannot-verify" ] }+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "query"+              , description = Some+                  "Repository-relative file holding the checking query."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "computationRef"+              , description = Some "Canonical Attested Computation URI."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.UriWithScheme "mori")+              }+            , FieldRule::{+              , field = "stated"+              , description = Some "The value as stated in the copy."+              , cardinality = Cardinality.Scalar+              }+            ]+          }+        , guidance = Some+            "The opt-in check-gtm.py requires query or computation evidence for measured verdicts and verifies referenced artifact targets and local query files."+        }+      ]+    }
test/fixtures/catalogue/profiles/assurance/package.dhall view
@@ -12,4 +12,11 @@ -- repository owns is a `coordination.bugReports` entry; what recurs across -- repositories, or lives in a toolchain rather than in anybody's source, is a -- failure mode.-{ reviews = ./reviews.dhall, failureModes = ./failure-modes.dhall }+-- `verificationEvidence` records a claim about a system being put to the test+-- and what the run and independent verifier concluded.+-- Claim checks record a test of wording against data, not a software run.+{ claimChecks = ./claim-checks.dhall+, reviews = ./reviews.dhall+, failureModes = ./failure-modes.dhall+, verificationEvidence = ./verification-evidence.dhall+}
+ test/fixtures/catalogue/profiles/assurance/verification-evidence.dhall view
@@ -0,0 +1,490 @@+--| Shared profile for verification evidence.+--+-- ## Evidence and identity+--+-- One Verification Run is an immutable event: one execution of one scenario at+-- exact revisions, or one comparison of recorded runs. It links to digest-pinned+-- data in durable storage and never contains measurements. An Attested Computation+-- defines how a result is produced and independently checked; an Attestation+-- records the verifier's conclusion. All three live in one bundle so runs can+-- resolve local VC-N computation handles. Definitions use stable handles; runs+-- and attestations use paths because concurrent writers cannot safely allocate+-- sequential handles with `okf id next`. A runId identifies the event even in+-- `okf concepts --json`, whose rows omit paths; a timestamp is not identity.+--+-- ## Scope and limits+--+-- `verified` is an append-only confirmation on a run; the Attestation is the+-- separate evidence of what was checked. A tool never writes a `human:` actor.+-- Event records take neither status nor stale_after because they are not+-- redrafted and do not decay. Definition records take OKF's v0.2 pair.+-- Runtime-specific layer and cost-tier vocabularies are open here; a consumer+-- can narrow them with a profile-scope overlay. The descriptor cannot check+-- digest or revision hex lengths, UUIDv7 identity, data reachability, or Git+-- immutability; consumers check those locally. Markdown under references/ is a+-- concept and would need another declared type, so runnable reference files+-- are non-Markdown. No legacyTimestamp field exists in OKF v0.2.+let Profile = ../../Profile/Type.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let PathReferenceRule = okf.defaults.PathReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let v02 = ../../Profile/V02.dhall++let kinds = [ "correctness", "concurrency", "soak", "benchmark" ]++let placements = [ "local", "cell" ]++let outcomes =+      [ "passed"+      , "failed"+      , "errored"+      , "inconclusive"+      , "infrastructure-failure"+      ]++let comparisonVerdicts =+      [ "pass", "regression", "inconclusive", "infrastructure-failure" ]++let purposes = [ "nightly", "release", "baseline", "investigation" ]++let dataKinds =+      [ "run-spec"+      , "run-result"+      , "manifest"+      , "cell-manifest"+      , "samples"+      , "series"+      , "verdicts"+      , "diagnosis"+      , "logs"+      , "comparison"+      ]++let checkNames =+      [ "digests-match"+      , "revisions-resolve"+      , "cohort-matches-plan"+      , "verdict-recomputed"+      , "environment-captured"+      , "clean-worktree"+      ]++let scalar =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let enum =+      \(name : Text) ->+      \(description : Text) ->+      \(allowedValues : List Text) ->+        scalar name description // { allowedValues }++let formatted =+      \(name : Text) ->+      \(description : Text) ->+      \(format : FieldFormat) ->+        scalar name description // { format = Some format }++let list =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.List+        }++let nScalar =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let nEnum =+      \(name : Text) ->+      \(description : Text) ->+      \(allowedValues : List Text) ->+        nScalar name description // { allowedValues }++let nFormatted =+      \(name : Text) ->+      \(description : Text) ->+      \(format : FieldFormat) ->+        nScalar name description // { format = Some format }++let nPaths =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.List+        , path = Some PathReferenceRule::{=}+        }++let nPath =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , path = Some PathReferenceRule::{=}+        }++let bundlePath =+      \(name : Text) ->+      \(description : Text) ->+        scalar name description // { path = Some PathReferenceRule::{=} }++let computationRef = Some HandleReferenceRule::{ localPrefix = "VC" }++let isRun = Some { field = "recordKind", hasValue = [ "run" ] }++let isComparison = Some { field = "recordKind", hasValue = [ "comparison" ] }++let nameValue =+      NestedRules::{+      , required =+        [ nScalar "name" "Name, as the harness spells it."+        , nScalar "value" "Value the run used."+        ]+      }++let attestedComputation =+      TypeRule::{+      , type = "Attested Computation"+      , description = Some+          "How one outcome, verdict or figure is computed from raw run data, and how a deterministic verifier re-checks it."+      , pathPattern = Some "computations/*"+      , idPrefix = Some "VC"+      , frontmatter = FrontmatterRules::{+        , required =+          [ formatted+              "computationId"+              "Bundle-scoped stable VC-N handle."+              (FieldFormat.DocumentHandle "VC")+          , scalar "runtime" "How the computation is run."+          , scalar+              "algorithm"+              "Identifier the harness writes into its documents."+          , formatted+              "algorithmVersion"+              "A change that can alter a result takes a new VC handle."+              FieldFormat.NonNegativeInteger+          , enum+              "produces"+              "What the computation yields."+              [ "outcome", "verdict", "diagnosis", "comparison", "summary" ]+          ,     list "inputs" "Data-link kinds the computation reads."+            //  { allowedValues = dataKinds }+          , scalar "implementation" "Module implementing the algorithm."+          ,     list "parameters" "Typed named holes; empty when it takes none."+            //  { elementFields = Some NestedRules::{+                  , required =+                    [ nScalar "name" "The name the computation binds."+                    , nScalar "type" "What kind of value it takes."+                    ]+                  , optional =+                    [ nFormatted+                        "required"+                        "Whether a caller must supply it."+                        FieldFormat.Boolean+                    ]+                  }+                }+          , FieldRule::{+            , field = "executor"+            , description = Some "How a run is performed and what it returns."+            , objectFields = Some NestedRules::{+              , required =+                [ nPath "resource" "Run instructions: a non-Markdown file here."+                ,     nScalar "receipt" "Run-directory documents a run returns."+                  //  { cardinality = Cardinality.List }+                ]+              }+            }+          , FieldRule::{+            , field = "attester"+            , description = Some "Deterministic code that re-checks a run."+            , objectFields = Some NestedRules::{+              , required =+                [ nPath "resource" "The verifier: a non-Markdown file here." ]+              }+            }+          ]+        , optional =+          [ v02.status+          , v02.staleAfter+          ,     list "appliesTo" "Evidence kinds whose runs may name it."+            //  { allowedValues = kinds }+          , bundlePath "computation" "The computation file, when not inline."+          ,     scalar "supersedes" "The definition this one replaces."+            //  { reference = computationRef }+          ]+        }+      }++let componentMembers =+      NestedRules::{+      , required =+        [ nFormatted+            "project"+            "Mori URI of the owning project."+            (FieldFormat.UriWithScheme "mori")+        , nScalar "package" "Cabal package name."+        , nScalar "version" "Exact resolved version."+        , nEnum "source" "Where the solver took it from." [ "hackage", "git" ]+        ,     nScalar "revision" "Full 40-character commit."+          //  { when = Some { field = "source", hasValue = [ "git" ] } }+        ]+      }++let environmentMembers =+      NestedRules::{+      , required =+        [ nScalar "os" "Operating system."+        , nScalar "arch" "CPU architecture."+        , nScalar "cpuModel" "CPU model string."+        , nFormatted "cores" "Logical cores." FieldFormat.NonNegativeInteger+        , nFormatted+            "memoryBytes"+            "Physical memory."+            FieldFormat.NonNegativeInteger+        , nScalar "ghc" "Compiler that built the harness."+        , nScalar "postgres" "PostgreSQL server version."+        ]+      , optional =+        [ nScalar "kernel" "Kernel release."+        , nScalar "machineType" "Cloud machine type of the driver."+        , nScalar "cell" "Name of the leased cell."+        , nScalar "cellRun" "The cell's own identifier for the leased run."+        , nScalar "zone" "Cloud zone."+        , nScalar "kafka" "Broker version, when a broker took part."+        ]+      }++let dataMembers =+      NestedRules::{+      , required =+        [ nEnum "kind" "What the object is." dataKinds+        , nFormatted+            "uri"+            "Where the object lives in durable storage."+            FieldFormat.Uri+        , nScalar "digest" "Lowercase 64-hex SHA-256 of the object."+        , nScalar "mediaType" "IANA media type."+        , nFormatted "bytes" "Object size." FieldFormat.NonNegativeInteger+        ]+      }++let comparisonMembers =+      NestedRules::{+      , required =+        [ nEnum "verdict" "What the comparison concluded." comparisonVerdicts+        , nEnum+            "factor"+            "What differs between the arms."+            [ "cohort", "harness", "dimension", "knob" ]+        , nScalar "baselineValue" "The factor's value on the baseline arm."+        , nScalar "candidateValue" "The factor's value on the candidate arm."+        , nEnum+            "design"+            "How the arms were interleaved."+            [ "abba", "baab", "sequential" ]+        , nPaths "baselineRuns" "Recorded runs of the baseline arm."+        , nPaths "candidateRuns" "Recorded runs of the candidate arm."+        ]+      , optional =+        [ nScalar "factorName" "Which dimension, knob or package differs." ]+      }++let verificationRun =+      TypeRule::{+      , type = "Verification Run"+      , description = Some+          "One recorded run, or one recorded comparison of runs: what ran, against what, where, with which outcome, and where the data is."+      , pathPattern = Some "runs/*/*/*/*"+      , frontmatter = FrontmatterRules::{+        , required =+          [ scalar "runId" "UUIDv7 of the record. Equals the file name."+          , enum+              "recordKind"+              "One run, or a comparison of runs."+              [ "run", "comparison" ]+          , enum "purpose" "Why this was recorded." purposes+          , scalar "scenario" "Scenario identifier: layer/component/kind/name."+          , scalar "layer" "Runtime layer the scenario isolates."+          , scalar "component" "Component inside the layer."+          , enum "kind" "Kind of evidence." kinds+          , scalar "tier" "Cost tier."+          , enum "placement" "Where it ran." placements+          , enum "outcome" "What came of it." outcomes+          , formatted "startedAt" "UTC start." FieldFormat.Rfc3339Utc+          , formatted "finishedAt" "UTC finish." FieldFormat.Rfc3339Utc+          , formatted+              "subject"+              "Mori URI of the most specific runtime artifact under test."+              (FieldFormat.UriWithScheme "mori")+          , enum "subjectKind" "What `subject` names." [ "project", "package" ]+          , scalar "harnessRevision" "Full 40-character commit of the harness."+          , formatted+              "harnessDirty"+              "Whether the harness was built from a modified tree."+              FieldFormat.Boolean+          ,     list "computations" "Definitions that produced the outcome."+            //  { reference = computationRef }+          ,     list "data" "Digest-pinned links to the data."+            //  { elementFields = Some dataMembers, uniqueBy = Some "uri" }+          ,     scalar "cohort" "Name of the cohort the build linked."+            //  { when = isRun }+          ,     scalar "solverPlanHash" "Hash of the resolved solver plan."+            //  { when = isRun }+          ,     list "components" "Every runtime package the build linked."+            //  { elementFields = Some componentMembers+                , uniqueBy = Some "package"+                , when = isRun+                }+          , FieldRule::{+            , field = "environment"+            , description = Some "Flat excerpt of the environment fingerprint."+            , objectFields = Some environmentMembers+            , when = isRun+            }+          ,     formatted+                  "seed"+                  "Seed of every random choice."+                  FieldFormat.NonNegativeInteger+            //  { when = isRun }+          ,     scalar+                  "compatibilityKey"+                  "64-hex digest of what must match for two runs to be comparable."+            //  { when = isRun }+          , FieldRule::{+            , field = "comparison"+            , description = Some "The arms and the verdict."+            , objectFields = Some comparisonMembers+            , when = isComparison+            }+          ]+        , optional =+          [     list "knobs" "Knob values the run used."+            //  { elementFields = Some nameValue, uniqueBy = Some "name" }+          ,     list "dimensions" "Dimension values the run used."+            //  { elementFields = Some nameValue, uniqueBy = Some "name" }+          ,     list "knownDefects" "Known-defect references of the scenario."+            //  { format = Some FieldFormat.Uri }+          ,     list "produced" "Mori URIs of reports this run caused."+            //  { format = Some (FieldFormat.UriWithScheme "mori") }+          , bundlePath+              "previousRun"+              "Latest earlier record of the same scenario and compatibility key."+          ]+        }+      }++let attestation =+      TypeRule::{+      , type = "Attestation"+      , description = Some+          "A deterministic verifier fetched a record's data, re-checked it, and this is what it concluded."+      , pathPattern = Some "attestations/*/*/*"+      , frontmatter = FrontmatterRules::{+        , required =+          [ scalar "attestationId" "UUIDv7. Equals the file name."+          , bundlePath "run" "The record attested."+          , formatted+              "attester"+              "The verifier, as an OKF actor."+              FieldFormat.Actor+          , scalar+              "attesterRevision"+              "Full 40-character commit of the verifier."+          , formatted "attestedAt" "UTC completion time." FieldFormat.Rfc3339Utc+          , enum+              "verdict"+              "What the verifier concluded."+              [ "confirmed", "refuted", "incomplete" ]+          ,     list "checks" "Every check, and what it found."+            //  { elementFields = Some NestedRules::{+                  , required =+                    [ nEnum "name" "Which check." checkNames+                    , nEnum+                        "result"+                        "What it found."+                        [ "passed", "failed", "skipped" ]+                    ]+                  , optional = [ nScalar "detail" "One line saying why." ]+                  }+                , uniqueBy = Some "name"+                }+          , list+              "dataDigests"+              "64-hex SHA-256 of every object fetched and matched."+          ]+        , optional =+          [ FieldRule::{+            , field = "exception"+            , description = Some "A human's acceptance of an anomaly."+            , objectFields = Some NestedRules::{+              , required =+                [ nFormatted+                    "authority"+                    "The human who accepted it."+                    FieldFormat.HumanActor+                , nScalar "reason" "Why the anomaly is acceptable."+                ]+              }+            }+          ]+        }+      }++let shared =+      Profile::{+      , name = "verification-evidence"+      , description = Some+          "Evidence about a runtime: definitions of how verdicts are computed, immutable records of runs that link to their data by digest, and attestations that a deterministic verifier re-checked that data."+      , okfVersion = "0.2"+      , requireBundleVersion = Some "0.2"+      , allowUnknownTypes = False+      , allowUnknownFields = False+      , idField = Some "computationId"+      , frontmatter = FrontmatterRules::{+        , required =+          [ scalar "type" "One of the three concept types."+          , scalar "title" "What this record is, in one line."+          , scalar "description" "One sentence a reader can evaluate alone."+          , v02.generated+          ]+        , optional = [ v02.verified ]+        }+      , types = [ attestedComputation, verificationRun, attestation ]+      }++in  shared
+ test/fixtures/catalogue/profiles/coordination/audiences.dhall view
@@ -0,0 +1,305 @@+--| Segments and personas describe the consumer side beside jobs. A persona is+-- not a job and never restates it. Its assessment rule is copied exactly from+-- jobs.dhall; keep the two policies in sync until factored into a shared block.+-- External-only references use SEG plus canonical foreign-handle patterns.+-- Nothing is recommended: untested drafts need no assessment or sources. House+-- status replaces OKF status/staleAfter. No legacyTimestamp exists for this new+-- v0.2 profile. Target type and query-file checks run in opt-in check-gtm.py.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++let externalOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "SEG"+          , allowLocal = False+          , externalUriSchemes = [ "mori" ]+          , externalUriPattern = Some (conceptUri prefix)+          }++let nestedScalar =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let assessment =+      FieldRule::{+      , field = "assessment"+      , description = Some+          "The authors' synthesis of research findings behind `validationStatus`."+      , objectFields = Some NestedRules::{+        , required =+          [ nestedScalar+              "rationale"+              "Why the cited findings justify the declared validation status."+          ,     nestedScalar+                  "assessedAt"+                  "UTC RFC3339 time the assessment was made."+            //  { format = Some FieldFormat.Rfc3339Utc }+          , NestedFieldRule::{+            , field = "findingRefs"+            , description = Some+                "Canonical Mori URIs of the product-research findings assessed."+            , cardinality = Cardinality.List+            , reference = externalOnly "PR"+            }+          ]+        }+      , when = Some+        { field = "validationStatus"+        , hasValue = [ "supported", "mixed", "challenged" ]+        }+      }++in  Profile::{+    , name = "audiences"+    , description = Some+        "Segments define populations; Personas name who holds jobs without restating those jobs."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "audienceId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ FieldRule::{+          , field = "type"+          , description = Some "The declared concept type."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "title"+          , description = Some "Human-readable concept title."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "description"+          , description = Some "One sentence describing the concept."+          , cardinality = Cardinality.Scalar+          }+        , v02.generated+        ]+      , optional =+        [ FieldRule::{+          , field = "tags"+          , description = Some "Producer-defined search and grouping tags."+          , cardinality = Cardinality.List+          }+        , reviewRule+        , v02.verified+        , v02.sources+        ]+      }+    , types =+      [ TypeRule::{+        , type = "Segment"+        , description = Some+            "A precisely defined population for coordinated work."+        , idPrefix = Some "SEG"+        , pathPattern = Some "segments/*"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "audienceId"+              , description = Some "Bundle-scoped stable SEG-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "SEG")+              }+            , FieldRule::{+              , field = "definition"+              , description = Some+                  "Population definition precise enough to query."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "status"+              , description = Some "Segment lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues = [ "draft", "active", "retired" ]+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "criteria"+              , description = Some+                  "Structured selectors with producer-owned vocabularies."+              , cardinality = Cardinality.List+              , elementFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "dimension"+                    , description = Some "Dimension being selected."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "operator"+                    , description = Some "Selection operation."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "value"+                    , description = Some "Selection value."+                    , cardinality = Cardinality.Scalar+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , FieldRule::{+              , field = "size"+              , description = Some "Segment size and how it was obtained."+              , cardinality = Cardinality.Any+              , objectFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "count"+                    , description = Some "Numeric population count."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "asOf"+                    , description = Some "Time of the count."+                    , cardinality = Cardinality.Scalar+                    , format = Some FieldFormat.Rfc3339Utc+                    }+                  , NestedFieldRule::{+                    , field = "method"+                    , description = Some "How the count was obtained."+                    , cardinality = Cardinality.Scalar+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , FieldRule::{+              , field = "query"+              , description = Some+                  "Repository-relative file defining membership."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "termRefs"+              , description = Some "Canonical vocabulary terms."+              , cardinality = Cardinality.List+              , reference = externalOnly "TERM"+              }+            , FieldRule::{+              , field = "parentSegmentRef"+              , description = Some "Broader Segment."+              , cardinality = Cardinality.Scalar+              , reference = Some HandleReferenceRule::{+                , localPrefix = "SEG"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "SEG")+                }+              }+            ]+          }+        }+      , TypeRule::{+        , type = "Persona"+        , description = Some+            "A research-assessed role and context; a persona is not a job."+        , idPrefix = Some "PERSONA"+        , pathPattern = Some "personas/*"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "audienceId"+              , description = Some "Bundle-scoped stable PERSONA-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "PERSONA")+              }+            , FieldRule::{+              , field = "role"+              , description = Some "Role represented by the persona."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "context"+              , description = Some "Circumstances in which the persona acts."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "status"+              , description = Some "Persona lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues = [ "draft", "active", "retired" ]+              }+            , FieldRule::{+              , field = "validationStatus"+              , description = Some "Research support for this persona."+              , cardinality = Cardinality.Scalar+              , allowedValues =+                [ "untested", "supported", "mixed", "challenged" ]+              }+            , assessment+            ]+          , optional =+            [ FieldRule::{+              , field = "jobRefs"+              , description = Some "Jobs held by this persona."+              , cardinality = Cardinality.List+              , reference = externalOnly "JOB"+              }+            , FieldRule::{+              , field = "segmentRefs"+              , description = Some "Segments containing this persona."+              , cardinality = Cardinality.List+              , reference = Some HandleReferenceRule::{+                , localPrefix = "SEG"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "SEG")+                }+              }+            , FieldRule::{+              , field = "goals"+              , description = Some "Producer-described goals."+              , cardinality = Cardinality.List+              }+            , FieldRule::{+              , field = "objections"+              , description = Some "Producer-described objections."+              , cardinality = Cardinality.List+              }+            , FieldRule::{+              , field = "channels"+              , description = Some "Channels used by the persona."+              , cardinality = Cardinality.List+              }+            ]+          }+        , guidance = Some+            "The opt-in check-gtm.py verifies that assessment references name current Findings and that other concept targets have the required types."+        }+      ]+    }
+ test/fixtures/catalogue/profiles/coordination/campaigns.dhall view
@@ -0,0 +1,466 @@+--| Campaigns are coordinated work with a lifecycle, beside features and designs.+-- Readouts reuse product-research Studies and Findings; reviews use ReviewRule.+-- External-only references use this profile’s CMP prefix as the engine requires,+-- then constrain the foreign handle by a canonical URI pattern. Nothing is+-- recommended: draft campaigns may have no review or evidence. Status is a house+-- vocabulary, so OKF status/staleAfter are absent (ADR-1). legacyTimestamp is absent+-- because this shared profile starts at v0.2. Unsupported conjunctions and target+-- types are enforced by the opt-in check-gtm.py, not a wider schema.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++let externalOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "CMP"+          , allowLocal = False+          , externalUriSchemes = [ "mori" ]+          , externalUriPattern = Some (conceptUri prefix)+          }++let hypothesis = ../../Profile/Hypothesis.dhall++in  Profile::{+    , name = "campaigns"+    , description = Some+        "Campaigns and their emails coordinate purpose, audience, delivery and research evaluation."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "campaignId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ FieldRule::{+          , field = "type"+          , description = Some "The declared concept type."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "title"+          , description = Some "Human-readable concept title."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "description"+          , description = Some "One sentence describing the concept."+          , cardinality = Cardinality.Scalar+          }+        , v02.generated+        ]+      , optional =+        [ FieldRule::{+          , field = "tags"+          , description = Some "Producer-defined search and grouping tags."+          , cardinality = Cardinality.List+          }+        , reviewRule+        , v02.verified+        , v02.sources+        ]+      }+    , types =+      [ TypeRule::{+        , type = "Campaign"+        , description = Some+            "Coordinated work carrying a hypothesis, announcement, or engagement purpose."+        , idPrefix = Some "CMP"+        , pathPattern = Some "*/campaign"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "campaignId"+              , description = Some "Bundle-scoped stable CMP-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "CMP")+              }+            , FieldRule::{+              , field = "purpose"+              , description = Some+                  "Primary purpose of the coordinated campaign."+              , cardinality = Cardinality.Scalar+              , allowedValues = [ "hypothesis", "announcement", "engagement" ]+              }+            , FieldRule::{+              , field = "status"+              , description = Some "Campaign coordination lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues =+                [ "drafting"+                , "in-review"+                , "approved"+                , "sending"+                , "measuring"+                , "read-out"+                , "cancelled"+                ]+              }+            , FieldRule::{+              , field = "owners"+              , description = Some+                  "Actors or canonical Mori URIs accountable for the campaign."+              , cardinality = Cardinality.List+              }+            ,     hypothesis+              //  { when = Some+                    { field = "purpose", hasValue = [ "hypothesis" ] }+                  }+            , FieldRule::{+              , field = "announcement"+              , description = Some+                  "Announced features and intended availability."+              , cardinality = Cardinality.Any+              , when = Some { field = "purpose", hasValue = [ "announcement" ] }+              , objectFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "featureRefs"+                    , description = Some+                        "Canonical URIs of the announced Features."+                    , cardinality = Cardinality.List+                    , reference = externalOnly "FEAT"+                    }+                  , NestedFieldRule::{+                    , field = "liveBy"+                    , description = Some "Intended availability deadline."+                    , cardinality = Cardinality.Scalar+                    , format = Some FieldFormat.Rfc3339Utc+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , FieldRule::{+              , field = "engagement"+              , description = Some "Behavior this campaign seeks and why."+              , cardinality = Cardinality.Any+              , when = Some { field = "purpose", hasValue = [ "engagement" ] }+              , objectFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "behavior"+                    , description = Some "The behavior to encourage."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "why"+                    , description = Some "Why the behavior matters."+                    , cardinality = Cardinality.Scalar+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , FieldRule::{+              , field = "readout"+              , description = Some+                  "Decision and research findings evaluating the campaign."+              , cardinality = Cardinality.Any+              , when = Some { field = "status", hasValue = [ "read-out" ] }+              , objectFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "decision"+                    , description = Some+                        "Decision taken in light of the findings."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "findingRefs"+                    , description = Some "Canonical result Finding URIs."+                    , cardinality = Cardinality.List+                    , reference = externalOnly "PR"+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , FieldRule::{+              , field = "cancellationReason"+              , description = Some "Why the campaign was cancelled."+              , cardinality = Cardinality.Scalar+              , when = Some { field = "status", hasValue = [ "cancelled" ] }+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "secondaryPurposes"+              , description = Some+                  "Additional purposes whose blocks also apply."+              , cardinality = Cardinality.List+              , allowedValues = [ "hypothesis", "announcement", "engagement" ]+              }+            , FieldRule::{+              , field = "audienceRefs"+              , description = Some "Canonical audience Segment URIs."+              , cardinality = Cardinality.List+              , reference = externalOnly "SEG"+              }+            , FieldRule::{+              , field = "audience"+              , description = Some+                  "Inline audience definitions for a corpus without a Segment bundle."+              , cardinality = Cardinality.List+              , elementFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "segment"+                    , description = Some "Segment name."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "definition"+                    , description = Some "Queryable population definition."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "size"+                    , description = Some "Population size at the stated time."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "asOf"+                    , description = Some "Time the population size describes."+                    , cardinality = Cardinality.Scalar+                    , format = Some FieldFormat.Rfc3339Utc+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , FieldRule::{+              , field = "primaryMetric"+              , description = Some+                  "Primary evaluation metric; observed values belong in findings or claim checks."+              , cardinality = Cardinality.Any+              , objectFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "name"+                    , description = Some "Stable name for this metric."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "metric"+                    , description = Some "What is counted or measured."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "unit"+                    , description = Some "Unit of measurement."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "direction"+                    , description = Some "Desired direction of change."+                    , cardinality = Cardinality.Scalar+                    , allowedValues = [ "increase", "decrease", "maintain" ]+                    }+                  , NestedFieldRule::{+                    , field = "method"+                    , description = Some "How the metric is obtained."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "population"+                    , description = Some "Population described by the metric."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "period"+                    , description = Some "Observation period for the baseline."+                    , cardinality = Cardinality.Scalar+                    }+                  ]+                , optional =+                  [ NestedFieldRule::{+                    , field = "baseline"+                    , description = Some+                        "Numeric starting value; evidence, not a target."+                    , cardinality = Cardinality.Scalar+                    }+                  ]+                }+              }+            , FieldRule::{+              , field = "window"+              , description = Some "Campaign evaluation interval."+              , cardinality = Cardinality.Any+              , objectFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "from"+                    , description = Some "Start of the evaluation window."+                    , cardinality = Cardinality.Scalar+                    , format = Some FieldFormat.Rfc3339Utc+                    }+                  , NestedFieldRule::{+                    , field = "to"+                    , description = Some "End of the evaluation window."+                    , cardinality = Cardinality.Scalar+                    , format = Some FieldFormat.Rfc3339Utc+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , FieldRule::{+              , field = "outcomeRefs"+              , description = Some+                  "Named job outcomes this work is intended to move."+              , cardinality = Cardinality.List+              , elementFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "jobRef"+                    , description = Some "Canonical job URI."+                    , cardinality = Cardinality.Scalar+                    , reference = externalOnly "JOB"+                    }+                  , NestedFieldRule::{+                    , field = "outcomeName"+                    , description = Some+                        "Name of an outcome declared by that job."+                    , cardinality = Cardinality.Scalar+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , FieldRule::{+              , field = "jobRefs"+              , description = Some "Customer jobs this campaign serves."+              , cardinality = Cardinality.List+              , reference = externalOnly "JOB"+              }+            , FieldRule::{+              , field = "studyRef"+              , description = Some "Canonical experiment Study URI."+              , cardinality = Cardinality.Scalar+              , reference = externalOnly "PR"+              }+            , FieldRule::{+              , field = "launchRef"+              , description = Some "Canonical Launch URI."+              , cardinality = Cardinality.Scalar+              , reference = externalOnly "LAUNCH"+              }+            , FieldRule::{+              , field = "chapters"+              , description = Some "Chapter labels in scope."+              , cardinality = Cardinality.List+              }+            ]+          }+        , guidance = Some+            "Approval and sending require the responsible owners’ actual review and send evidence; dates alone never promote the lifecycle. The opt-in check-gtm.py verifies secondary purpose blocks, experiment-study targets, result-finding targets, metric context and reference targets that descriptors cannot express."+        }+      , TypeRule::{+        , type = "Campaign Email"+        , description = Some+            "One email or regional variant in a coordinated campaign."+        , idPrefix = Some "EMAIL"+        , pathPattern = Some "*/emails/*"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "campaignId"+              , description = Some "Bundle-scoped stable EMAIL-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "EMAIL")+              }+            , FieldRule::{+              , field = "campaignRef"+              , description = Some "Campaign this email belongs to."+              , cardinality = Cardinality.Scalar+              , reference = Some HandleReferenceRule::{+                , localPrefix = "CMP"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "CMP")+                }+              }+            , FieldRule::{+              , field = "sequence"+              , description = Some+                  "Ordering within the campaign; variants may share it."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "status"+              , description = Some "Email preparation and send lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues =+                [ "draft", "approved", "scheduled", "sent", "cancelled" ]+              }+            , FieldRule::{+              , field = "sentAt"+              , description = Some "Actual send time."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Rfc3339Utc+              , when = Some { field = "status", hasValue = [ "sent" ] }+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "subject"+              , description = Some "Chosen subject line."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "subjectVariants"+              , description = Some "Producer-owned subject variants."+              , cardinality = Cardinality.Any+              }+            , FieldRule::{+              , field = "cta"+              , description = Some "Call to action."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "sendBy"+              , description = Some "Planned send deadline."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Rfc3339Utc+              }+            , FieldRule::{+              , field = "audienceRefs"+              , description = Some "Audience Segment URIs."+              , cardinality = Cardinality.List+              , reference = externalOnly "SEG"+              }+            , FieldRule::{+              , field = "landingPageRef"+              , description = Some "Canonical Landing Page URI."+              , cardinality = Cardinality.Scalar+              , reference = externalOnly "LP"+              }+            ]+          }+        }+      ]+    }
test/fixtures/catalogue/profiles/coordination/capabilities.dhall view
@@ -13,7 +13,11 @@ --     that omission is the profile's single most load-bearing decision. --   * A capability that only exists when several repositories cooperate is NOT a --     capability record either — no single repository can assert it or prove it.---     It belongs to the consuming repository as a use-case feature.+--     It belongs to the consumer as product behavior: a standalone feature+--     (`coordination.features`) or an inline use-case feature. A feature may+--     name the capabilities contributing to it through `capabilityRefs`; this+--     profile stores no list of features in return, and a capability a+--     feature still needs is an improvement request, not a planned capability. --   * Granularity: one capability is one thing a consumer can adopt AND verify --     independently. Where two candidates always ship together and are proven by --     the same evidence, they are one capability. A catalog with one record per@@ -159,7 +163,7 @@ in  Profile::{     , name = "capabilities"     , description = Some-        "Consumer-facing catalog of what a repository provides today: stable CAP-N handles, an explicit compatibility promise, and evidence. Provision claims only — absent capabilities are improvement requests, and capabilities that span repositories are use-case features owned by the consumer. The house `reviews` family and OKF `verified` coexist: `reviews` records far more than `verified` can, so an approving `reviews` entry should also be mirrored into `verified` to keep the derived trust tier accurate."+        "Consumer-facing catalog of what a repository provides today: stable CAP-N handles, an explicit compatibility promise, and evidence. Provision claims only — absent capabilities are improvement requests, and behavior that spans repositories is a feature owned by the consumer, standalone or inline in a use case. The house `reviews` family and OKF `verified` coexist: `reviews` records far more than `verified` can, so an approving `reviews` entry should also be mirrored into `verified` to keep the derived trust tier accurate."     , okfVersion = "0.2"     , requireBundleVersion = Some "0.2"     , allowUnknownTypes = False
+ test/fixtures/catalogue/profiles/coordination/designs-for.dhall view
@@ -0,0 +1,610 @@+--| Builder for the designs profile: design work for one surface (a page or a+-- self-contained part of one), split by the question each phase answers.+-- ADR-19 records the boundaries this profile draws.+--+-- `designs.dhall` applies this with no house conventions and is the export a+-- consumer normally selects. A house that wants a closed list of viewer axes+-- calls the builder itself:+--+--     Profiles.coordination.designsFor+--       { viewerAxisNames = [ "plan", "device" ] }+--+-- One folder per surface:+--+--   <surface>/brief       Design Brief     BRIEF-N   why / what+--   <surface>/breadboard  Breadboard       BB-N      how — structure+--   <surface>/design      Detailed Design  DES-N     how — presentation+--+--+-- ## Implementation is not a phase here+--+-- The fourth phase, implementation, is tracked where the catalog already+-- tracks delivery: the `coordination.features` a breadboard's affordances name+-- (status, owners, acceptance criteria, delivery evidence), the work that+-- builds them, and the checks against the brief's success criteria. Storing an+-- `implemented` status here would copy delivery state that the features own+-- (ADR-17).+--+--+-- ## Jobs and features are referenced, never restated+--+-- Customer jobs and their outcomes are canonical `coordination.jobs` concepts.+-- A brief links them (`jobs[].jobRef`, `outcomeRefs`) and gives each a short+-- local name; it never restates the statement. Affordances name the+-- `coordination.features` that deliver them. Every reference into another+-- bundle is external only, with the target prefix fixed by+-- `externalUriPattern` (ADR-17).+--+-- A surface's own chain — `brief` on a breadboard, `breadboard` on a detailed+-- design — is local handles only (ADR-19). `supersededBy` may also name a+-- concept in another bundle, by canonical URI with the same prefix.+--+--+-- ## Viewers, subject states, axes and scenarios+--+-- The brief declares who looks (viewers), the states the thing shown can be in+-- (subject states), the switches that modulate either (viewer and subject+-- axes) and the scenarios the surface must work in, at least one per viewer ×+-- subject state. The breadboard says what each viewer gets. The detailed+-- design draws scenarios and says, in one line each, which drawn scenario an+-- undrawn one equals.+--+-- Viewer axes are the attributes every viewer has on every page of a product —+-- a plan, a role, a device — so every brief must answer each of them. Which+-- attributes those are is a house decision, so the names are open unless the+-- house closes them through `viewerAxisNames`; a closed list is what stops a+-- brief from misspelling one. Subject axes are page-specific and always open.+--+-- These cross-document invariants — viewer names declared by the brief,+-- affordances and places declared by the breadboard, scenario coverage — are+-- not expressible in a descriptor. The type guidance names them so an author+-- reads them, per ADR-18.+--+--+-- ## Decisions and questions are shared by a surface's documents+--+-- Decision ids (D-N) and question ids (Q-N) are unique across a surface's three+-- documents, so "D-18" means one thing in a commit message. Each entry lives in+-- the document whose phase it settles.+--+--+-- ## Not a spec language+--+-- This profile gives agents the context for the work. Conditions and+-- exceptions go in prose (`note`, `rules`, the body) rather than in new fields.+--+--+-- ## Presence classes and status+--+-- Each type declares a house `status` (Policy one in `Profile/V02.dhall`), so+-- none takes OKF's `status` or `stale_after`. `reviews` is the only+-- unconditional recommendation (ADR-8); decisions, open questions and subject+-- axes are optional, because a complete document can lack each of them, except+-- that a detailed design records its chosen direction in `decisions` from+-- `chosen` on. Approval moves a document to `validated` or `designed`;+-- `verified` is then required and mirrors the approving `reviews` entry+-- (ADR-4).+--+-- `legacyTimestamp` is deliberately absent: the profile is introduced at v0.2.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let Nested = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let House = { viewerAxisNames : List Text }++let scalar =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let nscalar =+      \(name : Text) ->+      \(description : Text) ->+        Nested::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let nlist =+      \(name : Text) ->+      \(description : Text) ->+        Nested::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.List+        }++let none = [] : List Nested.Type++let records =+      \(name : Text) ->+      \(description : Text) ->+      \(key : Optional Text) ->+      \(required : List Nested.Type) ->+      \(optional : List Nested.Type) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.List+        , elementFields = Some { required, recommended = none, optional }+        , uniqueBy = key+        }++let whenStatus =+      \(hasValue : List Text) -> Some { field = "status", hasValue }++-- A concept URI in some producer's bundle; the bundle name is the producer's+-- choice, so it is never hard-coded.+let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++-- okf requires a reference's `localPrefix` to be a prefix this profile+-- declares, so references into other bundles borrow one and forbid local+-- values (ADR-17).+let externalOnly =+      \(localPrefix : Text) ->+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix+          , externalUriSchemes = [ "mori" ]+          , allowLocal = False+          , externalUriPattern = Some (conceptUri prefix)+          }++-- A surface's three documents live in one folder and chain by local handle+-- (ADR-19), so `brief` and `breadboard` take no external URI.+let localOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = prefix+          , externalUriSchemes = [] : List Text+          , allowSelf = False+          }++-- A replacement can live in another bundle once a surface moves, so+-- `supersededBy` also takes a canonical concept URI with the same prefix.+let localOrConcept =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = prefix+          , externalUriSchemes = [ "mori" ]+          , allowSelf = False+          , externalUriPattern = Some (conceptUri prefix)+          }++let designId =+      \(prefix : Text) ->+        FieldRule::{+        , field = "designId"+        , description = Some "Bundle-scoped stable ${prefix}-N handle."+        , cardinality = Cardinality.Scalar+        , format = Some (FieldFormat.DocumentHandle prefix)+        }++let status =+      \(values : List Text) ->+        FieldRule::{+        , field = "status"+        , description = Some "Workflow step. See the type guidance."+        , allowedValues = values+        , cardinality = Cardinality.Scalar+        }++let supersededBy =+      \(prefix : Text) ->+        FieldRule::{+        , field = "supersededBy"+        , description = Some "Later document replacing this one."+        , cardinality = Cardinality.Scalar+        , reference = localOrConcept prefix+        , when = whenStatus [ "retired" ]+        }++let verifiedWhen =+      \(values : List Text) ->+            v02.verified+        //  { description = Some "The approving review, mirrored from `reviews`."+            , when = whenStatus values+            }++-- Shared by all three types ------------------------------------------------++let decisions =+      records+        "decisions"+        "Settled questions a later phase must not reopen. D-N ids are unique across the surface's three documents."+        (Some "id")+        [     nscalar "id" "D-N handle."+          //  { format = Some (FieldFormat.DocumentHandle "D") }+        , nscalar "statement" "The decision."+        , Nested::{+          , field = "date"+          , description = Some "When it was decided."+          , cardinality = Cardinality.Scalar+          , format = Some FieldFormat.Date+          }+        ]+        [ nscalar "by" "Who decided." ]++let openQuestions =+      records+        "openQuestions"+        "Questions still open, each with an owner. Q-N ids are unique across the surface's three documents."+        (Some "id")+        [     nscalar "id" "Q-N handle."+          //  { format = Some (FieldFormat.DocumentHandle "Q") }+        , nscalar "question" "The question."+        , nscalar "owner" "Who answers it."+        ]+        none++-- Design Brief: why / what ------------------------------------------------++let viewers =+      records+        "viewers"+        "The kinds of viewer this surface distinguishes, declared per brief. Every `viewer` value in this brief and in its breadboard must be one of these names."+        (Some "name")+        [ nscalar "name" "Short identifier used by jobs, scenarios and visibility."+        , nscalar "definition" "Who this is, in one sentence."+        ]+        [ nscalar "computedFrom" "How the app decides a viewer is this kind." ]++let jobs =+      records+        "jobs"+        "The canonical jobs this surface serves, each under a short local name, and which viewers hold it. Where they arrive from is the breadboard's `connections`."+        (Some "name")+        [ nscalar "name" "Short local name used by scenarios and connections."+        ,     nscalar "jobRef" "Canonical Mori URI of the JOB concept."+          //  { reference = externalOnly "BRIEF" "JOB" }+        ]+        [ nlist "viewers" "Viewer names that hold this job." ]++let subjectStates =+      records+        "subjectStates"+        "The states the thing shown can be in, declared per brief — how much of a profile is filled in; open, shipped or cancelled for an order. Omit it when the subject has none, as on a form."+        (Some "name")+        [ nscalar "name" "Short identifier used by scenarios."+        , nscalar "definition" "What the subject has in this state, in facts that can be checked against the data, in one sentence."+        ]+        none++let outcomeRefs =+      records+        "outcomeRefs"+        "The job outcomes this surface is meant to move — the desired outcomes, owned by the jobs."+        (None Text)+        [     nscalar "jobRef" "Canonical Mori URI of a job in `jobs`."+          //  { reference = externalOnly "BRIEF" "JOB" }+        , nscalar "outcomeName" "Name of an outcome declared by that job."+        ]+        none++let successCriteria =+      records+        "successCriteria"+        "How the shipped surface is judged: observable conditions, each with how it will be checked. Implementation verifies these."+        (Some "id")+        [     nscalar "id" "Brief-local SC-N handle."+          //  { format = Some (FieldFormat.DocumentHandle "SC") }+        , nscalar "statement" "Observable condition that must hold."+        , nscalar "verification" "Procedure or evidence that will prove it."+        ]+        none++let applies =+      Nested::{+      , field = "applies"+      , description = Some+          "Whether this axis changes the surface. Words, not booleans: YAML would read yes/no as true/false."+      , allowedValues = [ "applies", "does-not-apply", "open" ]+      , cardinality = Cardinality.Scalar+      }++-- An empty `viewerAxisNames` leaves `name` open: okf treats an empty+-- `allowedValues` as no constraint.+let viewerAxes =+      \(house : House) ->+        records+          "viewerAxes"+          "Attributes of the viewer that every surface must consider, each answered explicitly: does it change this surface, and why. `does-not-apply` with a reason is a complete answer; silence is not."+          (Some "name")+          [ Nested::{+            , field = "name"+            , description = Some "Which viewer attribute."+            , allowedValues = house.viewerAxisNames+            , cardinality = Cardinality.Scalar+            }+          , applies+          , nscalar "because" "Why it applies or does not — the evidence, not the conclusion."+          ]+          [ nscalar "rules" "What changes when it applies, or which scenarios and open questions carry it." ]++let subjectAxes =+      records+        "subjectAxes"+        "Attributes of the thing being viewed, or of the context, that modulate this surface: independent switches that combine freely, unlike subject states. Page-specific, so names are open."+        (Some "name")+        [ nscalar "name" "Which attribute of the subject or context."+        , applies+        , nscalar "because" "Why it applies — the evidence."+        ]+        [ nscalar "rules" "What changes when it applies, or which scenarios and open questions carry it." ]++let scenarios =+      records+        "scenarios"+        "The situations the surface must work in, each with a concrete fixture: at least one per viewer × subject state, plus one for any axis that needs its own look. Later phases are checked against these."+        (Some "id")+        [ nscalar "id" "Short handle such as S1; stable once given."+        , nscalar "viewer" "A declared viewer name."+        , nscalar+            "fixture"+            "Who is looking, what data exists and what is missing, and the entry point — never what the page shows."+        ]+        [ nscalar "state" "A declared subject state."+        , nlist "axes" "Declared viewer and subject axes this scenario exercises."+        , nlist "jobs" "Local job names this scenario exercises."+        ]++let brief =+      \(house : House) ->+        TypeRule::{+        , type = "Design Brief"+        , description = Some+            "Why the surface exists and what it must achieve: the problem, who views it and for which jobs, the states the thing shown can be in, the outcomes it should move, the constraints, the scenarios it must work in, and the criteria it is judged by. No structure, no layout."+        , guidance = Some+            ''+            The body carries what only prose can: **Problem**, **Who it's for**, **Non-goals**, **Constraints** (cite decisions), principles, tone, and the baseline data that shows which subject state is the common one.++            okf checks the shapes, not the cross-references or the scenario coverage the `scenarios` description asks for. Read them: every `jobs[].viewers` and `scenarios[].viewer` is a declared viewer; every `scenarios[].state` a declared subject state; every `scenarios[].axes` entry a declared viewer or subject axis; every `scenarios[].jobs` entry a local job name; every `outcomeRefs[].jobRef` a `jobs[].jobRef`.++            `draft` → `validated` when the surface's approver signs off.+            ''+        , pathPattern = Some "*/brief"+        , idPrefix = Some "BRIEF"+        , frontmatter = FrontmatterRules::{+          , required =+            [ designId "BRIEF"+            , status [ "draft", "validated", "retired" ]+            , scalar "surface" "Route or component the surface is, e.g. /orders/[id]."+            , FieldRule::{+              , field = "origin"+              , description = Some "Mori project URI that owns the surface."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.UriWithScheme "mori")+              }+            , viewers+            , jobs+            , outcomeRefs // { when = whenStatus [ "validated" ] }+            , viewerAxes house // { when = whenStatus [ "validated" ] }+            , scenarios // { when = whenStatus [ "validated" ] }+            , successCriteria // { when = whenStatus [ "validated" ] }+            , verifiedWhen [ "validated" ]+            , supersededBy "BRIEF"+            ]+          , optional =+            [ subjectStates+            , subjectAxes+            , decisions+            , openQuestions+            , FieldRule::{+              , field = "useCases"+              , description = Some "Canonical Mori URIs of the use cases this surface realises."+              , cardinality = Cardinality.List+              , reference = externalOnly "BRIEF" "UC"+              }+            ]+          }+        }++-- Breadboard: how — structure -------------------------------------------++let places =+      records+        "places"+        "Where the viewer can be: the surface's own places and the external places that lead into it or that it leads to."+        (Some "name")+        [ nscalar "name" "Stable place name."+        , Nested::{+          , field = "kind"+          , description = Some+              "`surface` for a place this breadboard designs; `external` for one it only connects to."+          , allowedValues = [ "surface", "external" ]+          , cardinality = Cardinality.Scalar+          }+        , nscalar "description" "What the place is, in one sentence."+        ]+        none++let affordances =+      records+        "affordances"+        "What a viewer can read or do in each surface place, in words, with no layout. Each names the features that deliver it."+        (Some "name")+        [ nscalar "name" "Stable affordance name, used by visibility, connections and the detailed design."+        , nscalar "place" "A declared surface place."+        , nscalar "does" "What the viewer reads or does with it."+        ]+        [ Nested::{+          , field = "features"+          , description = Some "Canonical Mori URIs of the FEAT concepts that deliver it."+          , cardinality = Cardinality.List+          , reference = externalOnly "BB" "FEAT"+          }+        ]++let connections =+      records+        "connections"+        "How the viewer moves: from an external place or an affordance to a place. Connections from external places are the entry points and name the jobs that arrive by them."+        (None Text)+        [ nscalar "from" "A declared place or affordance."+        , nscalar "to" "A declared place."+        ]+        [ nscalar "carries" "Context passed along, such as a selected tab or filter in the URL."+        , nlist "jobs" "Brief job names that arrive by this connection."+        ]++let visibility =+      FieldRule::{+      , field = "visibility"+      , description = Some+          "Affordance × viewer, one entry each. `shown` and `hidden` are what they say; `collapsed` is present but de-emphasised (relevance, not permission); `filtered` shows the affordance with its items filtered per viewer; `prompts` turns an empty affordance into a call to fill it in. A condition or exception goes in `note`. The owner is a row like any other."+      , cardinality = Cardinality.List+      , elementFields = Some+        { required =+          [ nscalar "affordance" "A declared affordance name."+          , nscalar "viewer" "A viewer declared by the brief."+          , Nested::{+            , field = "rule"+            , description = Some "What this viewer gets."+            , allowedValues = [ "shown", "collapsed", "hidden", "filtered", "prompts" ]+            , cardinality = Cardinality.Scalar+            }+          ]+        , recommended = none+        , optional =+          [ nscalar "note" "Why, or the condition under which the rule changes."+          ]+        }+      }++let breadboard =+      TypeRule::{+      , type = "Breadboard"+      , description = Some+          "How the surface works, before what it looks like: places, the affordances in each, the connections between them, and what each viewer gets."+      , guidance = Some+          ''+          The body carries **ordering rules** written over the brief's viewers, subject states and axes — for example, which affordance comes first for each viewer — not a priority table per scenario.++          okf checks the shapes, not the cross-references. Read them: every `viewer` is declared by the brief, and every `connections[].jobs` entry is a brief job name; every `affordances[].place` is a declared `surface` place; every `visibility[].affordance`, `connections[].from` and `connections[].to` is declared here.++          `draft` → `validated` when the surface's approver signs off on the structure.+          ''+      , pathPattern = Some "*/breadboard"+      , idPrefix = Some "BB"+      , frontmatter = FrontmatterRules::{+        , required =+          [ designId "BB"+          , status [ "draft", "validated", "retired" ]+          ,     scalar "brief" "The brief this breadboard answers."+            //  { reference = localOnly "BRIEF" }+          , places+          , affordances+          , connections+          , visibility+          , verifiedWhen [ "validated" ]+          , supersededBy "BB"+          ]+        , optional = [ decisions, openQuestions ]+        }+      }++-- Detailed Design: how — presentation ------------------------------------++let states =+      records+        "states"+        "The states each affordance is designed in: with-data, and empty wherever the affordance can be empty; add absent (feature not shipped) and any domain state."+        (Some "affordance")+        [ nscalar "affordance" "A breadboard affordance."+        , nlist "states" "State names; every one appears on at least one final screen."+        ]+        none++let designArtifacts =+      records+        "designArtifacts"+        "Where the design lives."+        (Some "resource")+        [ nscalar "kind" "Tool or medium, such as figma, sketch, screenshot or video."+        , nscalar "resource" "A URL, or a path relative to this concept for a file in the repository."+        ]+        [ nscalar "note" "What this artifact shows." ]++let detailedDesign =+      TypeRule::{+      , type = "Detailed Design"+      , description = Some+          "What the breadboard looks like and how it behaves: the chosen direction, layouts, visual hierarchy, components, interaction details and every affordance state, with the final screens."+      , guidance = Some+          ''+          `exploring` (rough ideas, then options) → `chosen` (the direction is recorded in `decisions`) → `designed` (the final screens are exported, the `## Design handoff` section is written and the design review is signed off).++          By `designed`, every brief scenario is either in the `## Design handoff` table, which names the scenario of each screen, or has a line in the body saying which drawn scenario it equals and what differs, and every `states[].affordance` is declared by the breadboard. okf does not check either; read them.+          ''+      , pathPattern = Some "*/design"+      , idPrefix = Some "DES"+      , frontmatter = FrontmatterRules::{+        , required =+          [ designId "DES"+          , status [ "exploring", "chosen", "designed", "retired" ]+          ,     scalar "breadboard" "The breadboard this design presents."+            //  { reference = localOnly "BB" }+          , states+          , designArtifacts // { when = whenStatus [ "chosen", "designed" ] }+          , decisions // { when = whenStatus [ "chosen", "designed" ] }+          , verifiedWhen [ "designed" ]+          , supersededBy "DES"+          ]+        , optional = [ openQuestions ]+        }+      }++in  \(house : House) ->+      Profile::{+      , name = "designs"+      , description = Some+          "Design work per surface in three linked concepts — Design Brief (why/what), Breadboard (structure), Detailed Design (presentation). Jobs and features are canonical concepts referenced by Mori URI; implementation is tracked on the features. Approval requires `verified`, mirroring the approving `reviews` entry."+      , okfVersion = "0.2"+      , requireBundleVersion = Some "0.2"+      , allowUnknownTypes = False+      , idField = Some "designId"+      , frontmatter = FrontmatterRules::{+        , required =+          [ scalar "type" "Design Brief, Breadboard or Detailed Design."+          , scalar "title" "Human-readable title, usually the surface."+          , scalar "description" "One sentence: what this document settles."+          ,     v02.generated+            //  { description = Some "§5.2. Who produced this document's current content, and when." }+          ]+        , recommended = [ reviewRule ]+        , optional =+          [ FieldRule::{ field = "tags", cardinality = Cardinality.List }+          ,     v02.verified+            //  { description = Some "§5.2. Mirror an approving `reviews` entry here." }+          ]+        }+      , types = [ brief house, breadboard, detailedDesign ]+      }
+ test/fixtures/catalogue/profiles/coordination/designs.dhall view
@@ -0,0 +1,5 @@+--| Design work per surface — Design Brief, Breadboard and Detailed Design —+-- with no house conventions: viewer-axis names are open. See+-- `./designs-for.dhall` for the profile itself and for how a house closes the+-- viewer-axis names.+./designs-for.dhall { viewerAxisNames = [] : List Text }
+ test/fixtures/catalogue/profiles/coordination/features.dhall view
@@ -0,0 +1,300 @@+--| Profile for independently addressable product features with stable FEAT-N handles.+--+-- ## What a feature is+--+-- A feature is one coherent product behavior that can advance from discovery+-- to delivery and can appear in more than one use case. Its `FEAT-N` handle+-- does not depend on its title, its owning repository, or any screen layout,+-- so a use case, a request, a bug, and a future product-management UI can all+-- name it stably.+--+-- It sits beside the rest of the coordination family without replacing any of+-- it:+--+--   * a use case is a scenario; it names the features it relies on through+--     `featureRefs` and stores no copy of their delivery state;+--   * a capability is a producer's claim about behavior that already exists.+--     `capabilityRefs` names capabilities contributing to this feature. That+--     is not a claim that they deliver all of it, and missing producer behavior+--     is an improvement request, never a planned capability;+--   * a specification governs, or is proposed to govern, the feature's+--     contract. `specificationRefs` names it; a linked draft specification is+--     not a ratified obligation, and delivery does not prove conformance;+--   * an improvement request is repository work. `improvementRequests` names+--     requests delivering parts of this feature, and a request may point back+--     through its own `origin`. Neither direction is required.+--+-- No inverse lists are stored: where a feature is used, which bugs affect it,+-- and which requests originate from it are derived from the other side.+--+--+-- ## Acceptance criteria are scoped to their feature+--+-- `acceptanceCriteria` reuses the improvement-request shape: record-local+-- `AC-N` ids with a `statement` and a `verification`. A criterion is+-- identified by its owning feature URI plus its id, so a feature's `AC-1` and+-- a request's `AC-1` are unrelated, and satisfying one never satisfies the+-- other. `verification` names the expected procedure or evidence; it is not a+-- claim that the check already passed.+--+--+-- ## Delivery is not outcome+--+-- `deliveredAt` and `deliveryEvidence` show that the behavior was implemented+-- and accepted. They do not show that a customer job is better served; that is+-- a product-research question, and a delivered feature never changes a job's+-- `validationStatus`.+--+--+-- ## References to other profiles are external only+--+-- okf requires a reference rule's `localPrefix` to be an `idPrefix` this+-- profile declares, so every reference uses `FEAT` with `allowLocal = False`+-- and constrains its target family through `externalUriPattern`. Declaring a+-- foreign prefix such as `CAP` here would be a profile load failure. `owners`+-- is a list of Mori project URIs: a format, not a concept reference, so it+-- carries no reference rule. Whether a referenced concept exists and has the+-- right type needs the other bundle; the opt-in+-- `scripts/check-product-discovery.py` gate checks it until Mori does.+--+--+-- ## Presence classes+--+-- Nothing is recommended (ADR-8). A `discovered` feature may have no owners and+-- no criteria; both become required once a feature is `planned`,+-- `in-progress`, `blocked`, or `delivered`. A technical enabling feature may+-- name no job, and must not invent one to fill `jobRefs`. `priority` is a+-- producer's declared ordering signal for a UI, never a computed score.+--+-- No `guidance` is declared (ADR-12).+--+--+-- ## `legacyTimestamp` is deliberately absent+--+-- This profile is introduced at v0.2 and no v0.1 feature corpus exists.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let scalar =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let nestedScalar =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++-- `FEAT` is the only prefix this profile declares, so it is the `localPrefix`+-- of every reference, all of which name concepts in other bundles.+let externalOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "FEAT"+          , externalUriSchemes = [ "mori" ]+          , allowLocal = False+          , externalUriPattern = Some (conceptUri prefix)+          }++let referenceList =+      \(name : Text) ->+      \(prefix : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.List+        , reference = externalOnly prefix+        }++let whenStatus =+      \(hasValue : List Text) -> Some { field = "status", hasValue }++let committed = whenStatus [ "planned", "in-progress", "blocked", "delivered" ]++let acceptanceCriteria =+      FieldRule::{+      , field = "acceptanceCriteria"+      , description = Some+          "Feature-local product acceptance conditions with AC-N ids; not request criteria."+      , cardinality = Cardinality.List+      , elementFields = Some NestedRules::{+        , required =+          [     nestedScalar+                  "id"+                  "Stable feature-local AC-N handle for this condition."+            //  { format = Some (FieldFormat.DocumentHandle "AC") }+          , nestedScalar+              "statement"+              "Observable product condition that must hold for acceptance."+          , nestedScalar+              "verification"+              "Expected procedure or evidence that will prove the condition."+          ]+        }+      , uniqueBy = Some "id"+      , when = committed+      }++let outcomeRefs =+      FieldRule::{+      , field = "outcomeRefs"+      , description = Some+          "Named outcomes of jobs in `jobRefs` that this feature is meant to move."+      , cardinality = Cardinality.List+      , elementFields = Some NestedRules::{+        , required =+          [     nestedScalar "jobRef" "Canonical Mori URI of a job in `jobRefs`."+            //  { reference = externalOnly "JOB" }+          , nestedScalar "outcomeName" "Name of an outcome declared by that job."+          ]+        }+      }++in  Profile::{+    , name = "features"+    , description = Some+        "Independently addressable product features with stable FEAT handles: customer-visible behavior, a discovery-to-delivery lifecycle, owners and feature-local AC-N acceptance criteria once committed, delivery evidence, and canonical links to jobs, capabilities, specifications, and improvement requests. Delivery is not proof of outcome or conformance."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "featureId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ scalar "type" "The Feature concept type."+        , scalar "title" "Short, stable-sounding feature name."+        , scalar "description" "One sentence stating the feature."+        ,     v02.generated+          //  { description = Some+                  "§5.2. Who produced this feature's current content, and when."+              }+        ]+      , optional =+        [ FieldRule::{+          , field = "tags"+          , description = Some "Producer-defined search and grouping tags."+          , cardinality = Cardinality.List+          }+        , reviewRule+        ,     v02.verified+          //  { description = Some+                  "§5.2. Independent confirmations that this document is accurate. Mirror an approving `reviews` entry here."+              }+        ]+      }+    , -- `status` is a house delivery vocabulary (ADR-1); this profile does not+      -- splice OKF v0.2 §5.4's `status` or `stale_after`.+      types =+      [ TypeRule::{+        , type = "Feature"+        , description = Some+            "A coherent product behavior with its own identity and delivery lifecycle."+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "featureId"+              , description = Some "Bundle-scoped stable FEAT-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "FEAT")+              }+            ,     scalar+                    "status"+                    "Delivery state: discovered, planned, in-progress, delivered, blocked, deferred, or retired."+              //  { allowedValues =+                    [ "discovered"+                    , "planned"+                    , "in-progress"+                    , "delivered"+                    , "blocked"+                    , "deferred"+                    , "retired"+                    ]+                  }+            , scalar+                "behavior"+                "Proposed or actual customer-visible behavior."+            , FieldRule::{+              , field = "owners"+              , description = Some+                  "Mori project URIs accountable for delivering the feature."+              , cardinality = Cardinality.List+              , format = Some (FieldFormat.UriWithScheme "mori")+              , when = committed+              }+            , acceptanceCriteria+            ,     scalar+                    "deliveredAt"+                    "UTC RFC3339 time the behavior was delivered and accepted."+              //  { format = Some FieldFormat.Rfc3339Utc+                  , when = whenStatus [ "delivered" ]+                  }+            ,     v02.sources+              //  { field = "deliveryEvidence"+                  , description = Some+                      "Evidence that the behavior was delivered, in the shape of §5.1 sources."+                  , when = whenStatus [ "delivered" ]+                  }+            ]+          , optional =+            [ referenceList+                "jobRefs"+                "JOB"+                "Canonical Mori URIs of the customer jobs this feature serves."+            , outcomeRefs+            , referenceList+                "capabilityRefs"+                "CAP"+                "Canonical Mori URIs of producer capabilities contributing behavior."+            , referenceList+                "specificationRefs"+                "SPEC"+                "Canonical Mori URIs of specifications governing this feature."+            , referenceList+                "improvementRequests"+                "IR"+                "Canonical Mori URIs of requests delivering parts of this feature."+            ,     scalar+                    "priority"+                    "Producer-declared ordering signal: low, medium, high, or critical."+              //  { allowedValues = [ "low", "medium", "high", "critical" ] }+            ]+          }+        , pathPattern = Some "*"+        , idPrefix = Some "FEAT"+        }+      ]+    }
+ test/fixtures/catalogue/profiles/coordination/friction-log.dhall view
@@ -0,0 +1,293 @@+--| Profile for a friction log: the cost of doing work in a repository, recorded+-- before it is known to be a defect or a request.+--+-- ## What a friction entry is, and what it is not+--+-- A friction entry records that a surface — a document, an interface, a tool,+-- an environment, or a house process — cost an implementer material effort+-- while doing planned work. It states what was attempted, what happened+-- instead, what it cost, and what the implementer did about it. It makes no+-- claim about who is wrong, which is exactly what separates it from its two+-- coordination siblings:+--+--   * A bug report is a *broken provision claim*. Friction becomes a bug+--     report once the recording repository can say which published claim is+--     contradicted and how to reproduce it. Until then it stays friction.+--   * An improvement request is a *gap* a producer should close. Friction+--     becomes a request once someone can state the outcome they want.+--+-- Friction is therefore the intake queue in front of both: raw, first-person,+-- and cheap to write, so that a surface's owner can see across every consuming+-- repository where it costs the most before any of it has been triaged.+-- `status` records the triage outcome and `promotedTo` names the artifact that+-- took over.+--+-- A plan's Surprises & Discoveries section is a different thing again: it+-- holds findings that changed the plan or explain a non-obvious result.+-- Friction that also changed a plan is recorded in both places, each citing+-- the other.+--+-- Granularity: one entry is one surface costing effort once. The same surface+-- costing effort again under another plan is a second entry, because+-- recurrence is the signal this family exists to surface. `duplicateOf` is for+-- two entries describing the same occurrence, not the same cause.+--+--+-- ## `impact` is an observable consequence, not a mood+--+-- The four values are ordered by what happened to the work, and are assigned+-- by observation:+--+--   * `blocked`   — the planned path could not proceed; a human or a change+--                   outside the repository was needed.+--   * `detour`    — the work proceeded only through a workaround, which the+--                   entry must name.+--   * `slowdown`  — the intended path worked, but cost material time through+--                   retries, re-reading, or trial and error.+--   * `nuisance`  — no material cost; recorded because it will recur.+--+-- Priority is deliberately absent, for the reason `bug-reports` gives: it+-- changes with the schedule and has no place in a cross-repository record.+--+--+-- ## `kind` names the surface, not the cause+--+-- `kind` says what sort of thing cost the effort, so a surface's owner can+-- filter a corpus to what they own. It is not a root cause: a `documentation`+-- entry may turn out to be an interface defect, and promotion is where that+-- is recorded.+--+--+-- ## `origin` and `affects`+--+-- `origin` is the Mori URI of the project in which the friction was+-- experienced. `affects` is the URI of the project or artifact whose surface+-- cost the effort. They differ in the case this family exists for: a consumer+-- recording friction with a dependency. `affects` admits any absolute URI+-- rather than only `mori://`, because friction is often with a tool a house+-- does not register; a registered subject is always named by its canonical+-- Mori URI, and a house that registers everything it depends on may narrow+-- the format in its local descriptor.+--+--+-- ## Presence classes+--+-- Nothing is recommended (ADR-8). `workaround` is demanded once `impact` is+-- `detour`, because a detour is defined by having one. `promotedTo`,+-- `duplicateOf` and `resolution` are demanded by the status that gives each+-- its meaning.+--+-- `reviews` and `verified` are optional rather than recommended, which+-- departs from the other coordination profiles on purpose. An entry is a+-- first-person observation that is correct the moment it is written, and+-- demanding review provenance on every entry under `--strict` would price the+-- log out of the habit it exists to create. Triage, not review, is this+-- family's quality gate, and it is recorded in `status`.+--+-- `amended` records later changes that leave the entry standing — a status+-- change at triage — so `generated` keeps who observed the friction, as+-- `documentation.architectureDecisions` does for a decision.+--+--+-- ## The house `status` vocabulary+--+-- Per ADR-1 this profile declares a house lifecycle vocabulary on `status` and+-- therefore does NOT splice OKF v0.2 §5.4's `status` or §5.5's `stale_after`.+--+--+-- ## `legacyTimestamp` is deliberately absent+--+-- This profile is introduced at v0.2 and no v0.1 friction corpus exists.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let Nested = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let condition =+      \(field : Text) -> \(hasValue : List Text) -> { field, hasValue }++let scalar =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++-- One mapping per later change, newest last. `by` and `at` take the+-- `generated` formats so the two families read the same way.+let amended =+      FieldRule::{+      , field = "amended"+      , description = Some+          "Later changes that leave the entry standing, such as a status change at triage, newest last. `generated` keeps who observed the friction."+      , cardinality = Cardinality.List+      , elementFields = Some NestedRules::{+        , required =+          [ Nested::{+            , field = "by"+            , description = Some+                "§7. The actor responsible: `<producer>/<version>`, `human:<id>`, or `process:<id>`."+            , cardinality = Cardinality.Scalar+            , format = Some FieldFormat.Actor+            }+          , Nested::{+            , field = "at"+            , description = Some+                "UTC RFC3339 timestamp, ending in `Z`, for when this happened."+            , cardinality = Cardinality.Scalar+            , format = Some FieldFormat.Rfc3339Utc+            }+          , Nested::{+            , field = "change"+            , description = Some "What changed, in one sentence."+            , cardinality = Cardinality.Scalar+            }+          ]+        }+      }++in  Profile::{+    , name = "friction-log"+    , description = Some+        "The cost of doing work in a repository, recorded before it is known to be a defect or a request: one entry per surface that cost an implementer effort, with a stable FRIC handle, an impact graded by what happened to the work, the kind of surface, who felt it and whose surface it was, and a triage status naming the artifact that took it over. Behavior known to be wrong is a bug report; a gap someone can state is an improvement request."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "frictionId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ scalar "type" "The Friction Entry concept type."+        , scalar "title" "Short statement of what cost effort."+        , scalar+            "description"+            "One sentence naming the surface and the cost, evaluable without the body."+        ,     v02.generated+          //  { description = Some+                  "§5.2. Who observed the friction and wrote this entry, and when."+              }+        , FieldRule::{+          , field = "frictionId"+          , description = Some "Bundle-scoped stable FRIC-N handle."+          , cardinality = Cardinality.Scalar+          , format = Some (FieldFormat.DocumentHandle "FRIC")+          }+        , FieldRule::{+          , field = "status"+          , description = Some "Where triage has got to."+          , allowedValues =+            [ "logged", "promoted", "resolved", "accepted", "duplicate" ]+          , cardinality = Cardinality.Scalar+          }+        , -- Consequence, not priority. Take the most severe value that actually+          -- occurred; see the header for what each one means.+          FieldRule::{+          , field = "impact"+          , description = Some+              "What happened to the work, most severe first."+          , allowedValues = [ "blocked", "detour", "slowdown", "nuisance" ]+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "kind"+          , description = Some "The sort of surface that cost the effort."+          , allowedValues =+            [ "documentation", "interface", "tooling", "environment", "process" ]+          , cardinality = Cardinality.Scalar+          }+        ,     scalar+                "origin"+                "Mori URI of the project in which the friction was experienced."+          //  { format = Some (FieldFormat.UriWithScheme "mori") }+        , -- Any absolute URI, not only `mori://`: see the header.+              scalar+                "affects"+                "URI of the project or artifact whose surface cost the effort: its canonical Mori URI when registered, otherwise its canonical URL."+          //  { format = Some FieldFormat.Uri }+        , -- The next four are conditionally required, which okf spells+          -- `required` plus `when`: a `when` condition gates a presence demand,+          -- and an `optional` rule makes no demand to gate. Each stays checked+          -- whenever it is present under any other value.+              scalar+                "workaround"+                "What the implementer did instead. Demanded once `impact` is `detour`."+          //  { when = Some (condition "impact" [ "detour" ]) }+        ,     scalar+                "promotedTo"+                "URI of the bug report, improvement request, plan, or external issue that now tracks this friction. Demanded once `status` is `promoted`."+          //  { format = Some FieldFormat.Uri+              , when = Some (condition "status" [ "promoted" ])+              }+        , FieldRule::{+          , field = "duplicateOf"+          , description = Some+              "The entry this one duplicates, as a local FRIC-N handle or an external Mori URI. Demanded once `status` is `duplicate`."+          , cardinality = Cardinality.Scalar+          , reference = Some HandleReferenceRule::{+            , localPrefix = "FRIC"+            , externalUriSchemes = [ "mori" ]+            }+          , when = Some (condition "status" [ "duplicate" ])+          }+        ,     scalar+                "resolution"+                "How the cause went away, or why the house lives with it. Demanded once `status` is `resolved` or `accepted`."+          //  { when = Some (condition "status" [ "resolved", "accepted" ]) }+        ]+      , optional =+        [ scalar+            "affectedVersion"+            "Released version of the affecting surface the friction was met with; `unreleased` or `unknown` otherwise."+        , scalar+            "plan"+            "Repository-relative path or Mori URI of the plan being implemented when the friction occurred."+        , FieldRule::{+          , field = "tags"+          , description = Some "Producer-defined search and grouping tags."+          , cardinality = Cardinality.List+          }+        , amended+        , reviewRule+        ,     v02.verified+          //  { description = Some+                  "§5.2. Independent confirmations that this entry is accurate. A list of mappings, or one bare mapping."+              }+        ]+      }+    , types =+      [ TypeRule::{+        , type = "Friction Entry"+        , description = Some+            "One surface costing an implementer effort once, recorded before triage."+        , -- Two sentences, each one of ADR-18's kinds: the first is lifecycle+          -- meaning and who signs it off; the second is where body prose goes.+          guidance = Some+            ''+            An entry is `logged` when written and moves only at triage by the recording repository: to `promoted` once the artifact in `promotedTo` tracks it, to `resolved` once its cause is gone, to `accepted` once the house decides to live with it, or to `duplicate`.+            What was attempted and what happened instead, with evidence, go in the body under `## Attempted` and `## Encountered`.+            ''+        , pathPattern = Some "*"+        , idPrefix = Some "FRIC"+        }+      ]+    }
+ test/fixtures/catalogue/profiles/coordination/jobs.dhall view
@@ -0,0 +1,287 @@+--| Profile for canonical customer jobs with stable JOB-N handles.+--+-- ## What a job is+--+-- A job, in the Jobs-to-be-Done sense, is the progress a person is trying to+-- make in a particular situation, stated independently of any product, screen,+-- or implementation. A job stays `active` when one attempted solution fails:+-- the failure is evidence about the solution, not about whether the customer+-- still wants to make progress.+--+-- A use case may still carry an inline `jobs` record describing one scenario's+-- actor and circumstances. That record is a scenario snapshot; a `Job` concept+-- is the canonical statement the snapshot links to through `jobs[].jobRef`.+--+--+-- ## Research support is a declaration, not a computation+--+-- `validationStatus` says what the authors currently believe about whether+-- research supports this statement of the job: `untested`, `supported`,+-- `mixed`, or `challenged`. Anything other than `untested` demands an+-- `assessment` naming the product-research findings it synthesises and the+-- reasoning that connects them. Support is never derived by counting finding+-- stances, and it is never inferred from `verified`, which confirms that the+-- document is accurate rather than that the job is real.+--+--+-- ## Outcomes may be qualitative+--+-- Each outcome needs only a `name` and a `description`. The measurement+-- members (`metric`, `unit`, `direction`, `method`, `baseline`, `target`,+-- `population`, `period`) are optional because many jobs are understood+-- before anyone can measure them. okf cannot express "all of these or none of+-- these" between nested members, nor a general finite-number format, so the+-- opt-in `scripts/check-product-discovery.py` gate enforces that a measured+-- outcome names its metric, unit, direction, and method together, and that+-- `baseline` and `target` are finite numbers. A `target` is an aspiration and+-- never an observation; an observed value belongs in a finding's+-- `measurements`.+--+--+-- ## References to other profiles are external only+--+-- `assessment.findingRefs` names product-research findings, which live in a+-- bundle governed by `documentation.productResearch`. okf requires a reference+-- rule's `localPrefix` to be an `idPrefix` this profile declares, so the rule+-- uses `JOB` with `allowLocal = False` and constrains the target family with+-- `externalUriPattern`. Declaring a foreign `PR` prefix here would be a+-- profile load failure. Whether a cited finding exists, is a finding rather+-- than a study, and actually assesses this job is a cross-bundle question that+-- okf leaves to Mori; until Mori resolves it, the opt-in gate does.+--+--+-- ## Presence classes+--+-- Nothing is recommended. Per ADR-8 a field is recommended only when a+-- well-run corpus carries it, and an untested draft job routinely has no+-- review, no sources, and no assessment. `reviews` is optional for the same+-- reason `documentation.specifications` makes it optional: a draft nobody has+-- reviewed yet is complete for what it is.+--+-- No `guidance` is declared (ADR-12): there is no observed authoring failure+-- to correct yet.+--+--+-- ## `legacyTimestamp` is deliberately absent+--+-- This profile is introduced at v0.2 and no v0.1 job corpus exists.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let scalar =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let nestedScalar =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++-- A concept URI in some producer's bundle; the bundle name is the producer's+-- choice, so it is never hard-coded.+let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++-- `JOB` is the only prefix this profile declares, so it is the `localPrefix`+-- of every reference, including ones that may never be local.+let externalOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "JOB"+          , externalUriSchemes = [ "mori" ]+          , allowLocal = False+          , externalUriPattern = Some (conceptUri prefix)+          }++let outcomes =+      FieldRule::{+      , field = "outcomes"+      , description = Some+          "Desired results that show the job's progress, qualitative or measured."+      , cardinality = Cardinality.List+      , elementFields = Some NestedRules::{+        , required =+          [ nestedScalar "name" "Stable outcome name, unique within this job."+          , nestedScalar+              "description"+              "What the actor would observe when this outcome is achieved."+          ]+        , optional =+          [ nestedScalar "metric" "What is measured to track this outcome."+          , nestedScalar "unit" "Unit every baseline, target, and measurement uses."+          ,     nestedScalar+                  "direction"+                  "Which way the metric should move: `increase`, `decrease`, or `maintain`."+            //  { allowedValues = [ "increase", "decrease", "maintain" ] }+          , nestedScalar "method" "How the metric is obtained."+          , nestedScalar+              "baseline"+              "Measured starting value in `unit`, documented by a `sources` entry."+          , nestedScalar+              "target"+              "Aspired value in `unit`; never an observation."+          , nestedScalar "population" "Whose behavior the baseline describes."+          , nestedScalar "period" "When the baseline was observed."+          ]+        }+      , uniqueBy = Some "name"+      }++let assessment =+      FieldRule::{+      , field = "assessment"+      , description = Some+          "The authors' synthesis of research findings behind `validationStatus`."+      , objectFields = Some NestedRules::{+        , required =+          [ nestedScalar+              "rationale"+              "Why the cited findings justify the declared validation status."+          ,     nestedScalar+                  "assessedAt"+                  "UTC RFC3339 time the assessment was made."+            //  { format = Some FieldFormat.Rfc3339Utc }+          , NestedFieldRule::{+            , field = "findingRefs"+            , description = Some+                "Canonical Mori URIs of the product-research findings assessed."+            , cardinality = Cardinality.List+            , reference = externalOnly "PR"+            }+          ]+        }+      , when = Some+        { field = "validationStatus"+        , hasValue = [ "supported", "mixed", "challenged" ]+        }+      }++in  Profile::{+    , name = "jobs"+    , description = Some+        "Canonical Jobs-to-be-Done statements with stable JOB handles: the progress an actor seeks in a situation, qualitative or measured outcomes, and an explicit research assessment citing product-research findings. States customer progress, never a solution."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "jobId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ scalar "type" "The Job concept type."+        , scalar "title" "Short name for the progress the actor seeks."+        , scalar "description" "One sentence stating the job."+        ,     v02.generated+          //  { description = Some+                  "§5.2. Who produced this job's current content, and when."+              }+        ]+      , optional =+        [ FieldRule::{+          , field = "tags"+          , description = Some "Producer-defined search and grouping tags."+          , cardinality = Cardinality.List+          }+        , reviewRule+        ,     v02.verified+          //  { description = Some+                  "§5.2. Independent confirmations that this document is accurate. Mirror an approving `reviews` entry here."+              }+        ]+      }+    , -- `status` and `validationStatus` are house vocabularies (ADR-1); this+      -- profile does not splice OKF v0.2 §5.4's `status` or `stale_after`. See+      -- the header of ../../Profile/V02.dhall.+      types =+      [ TypeRule::{+        , type = "Job"+        , description = Some+            "Progress an actor seeks in a situation, independent of any solution."+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "jobId"+              , description = Some "Bundle-scoped stable JOB-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "JOB")+              }+            , scalar "actor" "Person or role trying to make progress."+            , scalar "situation" "Circumstance in which the job arises."+            , scalar "motivation" "Progress the actor wants to make."+            ,     scalar+                    "status"+                    "Lifecycle of this job statement: `draft`, `active`, or `retired`."+              //  { allowedValues = [ "draft", "active", "retired" ] }+            ,     scalar+                    "validationStatus"+                    "Declared research support: `untested`, `supported`, `mixed`, or `challenged`."+              //  { allowedValues =+                    [ "untested", "supported", "mixed", "challenged" ]+                  }+            , outcomes+            , assessment+            ]+          , optional =+            [ scalar+                "functionalContext"+                "Practical task constraints surrounding the job."+            , scalar+                "emotionalContext"+                "How the actor wants to feel, or avoid feeling."+            , scalar+                "socialContext"+                "How the actor wants to be perceived by others."+            , FieldRule::{+              , field = "relatedJobs"+              , description = Some+                  "Related local JOB handles or canonical Mori job URIs."+              , cardinality = Cardinality.List+              , reference = Some HandleReferenceRule::{+                , localPrefix = "JOB"+                , externalUriSchemes = [ "mori" ]+                , allowSelf = False+                , allowLocal = True+                , externalUriPattern = Some (conceptUri "JOB")+                }+              }+            ,     v02.sources+              //  { description = Some+                      "§5.1. Evidence this job statement and any baseline were derived from."+                  }+            ]+          }+        , pathPattern = Some "*"+        , idPrefix = Some "JOB"+        }+      ]+    }
+ test/fixtures/catalogue/profiles/coordination/launches.dhall view
@@ -0,0 +1,292 @@+--| Launches use the feature acceptance shape for readiness and the shared sources+-- shape for launch evidence. A planned date never proves publication or outcome.+-- Landing Pages link designs rather than duplicating layout. House lifecycles+-- replace OKF status/staleAfter; drafts need no review or evidence, so nothing is+-- recommended. All foreign references are canonical and external-only; LAUNCH and+-- LP references may be local within this profile. No legacyTimestamp exists.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++let externalOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "LAUNCH"+          , allowLocal = False+          , externalUriSchemes = [ "mori" ]+          , externalUriPattern = Some (conceptUri prefix)+          }++in  Profile::{+    , name = "launches"+    , description = Some+        "Launches coordinate go-live events; Landing Pages name the surfaces and their evidence."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "launchId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ FieldRule::{+          , field = "type"+          , description = Some "The declared concept type."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "title"+          , description = Some "Human-readable concept title."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "description"+          , description = Some "One sentence describing the concept."+          , cardinality = Cardinality.Scalar+          }+        , v02.generated+        ]+      , optional =+        [ FieldRule::{+          , field = "tags"+          , description = Some "Producer-defined search and grouping tags."+          , cardinality = Cardinality.List+          }+        , reviewRule+        , v02.verified+        , v02.sources+        ]+      }+    , types =+      [ TypeRule::{+        , type = "Launch"+        , description = Some+            "Coordinated go-live work with a deadline and explicit readiness conditions."+        , idPrefix = Some "LAUNCH"+        , pathPattern = Some "launches/*"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "launchId"+              , description = Some "Bundle-scoped stable LAUNCH-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "LAUNCH")+              }+            , FieldRule::{+              , field = "status"+              , description = Some "Launch coordination lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues = [ "planned", "ready", "launched", "cancelled" ]+              }+            , FieldRule::{+              , field = "liveBy"+              , description = Some "Intended UTC go-live deadline."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Rfc3339Utc+              }+            , FieldRule::{+              , field = "readiness"+              , description = Some+                  "Conditions for release and how each will be verified; not a pass declaration."+              , cardinality = Cardinality.List+              , when = Some+                { field = "status", hasValue = [ "ready", "launched" ] }+              , elementFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "id"+                    , description = Some "Launch-local AC-N condition handle."+                    , cardinality = Cardinality.Scalar+                    , format = Some (FieldFormat.DocumentHandle "AC")+                    }+                  , NestedFieldRule::{+                    , field = "statement"+                    , description = Some "Observable readiness condition."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "verification"+                    , description = Some+                        "Procedure or evidence that will verify the condition."+                    , cardinality = Cardinality.Scalar+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              , uniqueBy = Some "id"+              }+            , FieldRule::{+              , field = "launchedAt"+              , description = Some "Actual UTC launch time."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Rfc3339Utc+              , when = Some { field = "status", hasValue = [ "launched" ] }+              }+            ,     v02.sources+              //  { field = "launchEvidence"+                  , description = Some+                      "Evidence of the actual launch, in the shared sources shape."+                  , when = Some { field = "status", hasValue = [ "launched" ] }+                  }+            , FieldRule::{+              , field = "cancellationReason"+              , description = Some "Why the launch was cancelled."+              , cardinality = Cardinality.Scalar+              , when = Some { field = "status", hasValue = [ "cancelled" ] }+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "featureRefs"+              , description = Some "Features in the launch."+              , cardinality = Cardinality.List+              , reference = externalOnly "FEAT"+              }+            , FieldRule::{+              , field = "segmentRefs"+              , description = Some "Segments addressed."+              , cardinality = Cardinality.List+              , reference = externalOnly "SEG"+              }+            , FieldRule::{+              , field = "campaignRefs"+              , description = Some "Launch campaigns."+              , cardinality = Cardinality.List+              , reference = externalOnly "CMP"+              }+            , FieldRule::{+              , field = "landingPageRefs"+              , description = Some "Related Landing Pages."+              , cardinality = Cardinality.List+              , reference = Some HandleReferenceRule::{+                , localPrefix = "LP"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "LP")+                }+              }+            , FieldRule::{+              , field = "initiativeRef"+              , description = Some "Initiative coordinating the launch."+              , cardinality = Cardinality.Scalar+              , reference = externalOnly "INIT"+              }+            , FieldRule::{+              , field = "chapters"+              , description = Some "Producer chapter labels in scope."+              , cardinality = Cardinality.List+              }+            ]+          }+        , guidance = Some+            "Readiness describes conditions and verification, not that they passed. Launched records a go-live event and evidence, not proof of customer outcome."+        }+      , TypeRule::{+        , type = "Landing Page"+        , description = Some+            "A published or planned GTM surface; design work stays in the designs profile."+        , idPrefix = Some "LP"+        , pathPattern = Some "landing-pages/*"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "launchId"+              , description = Some "Bundle-scoped stable LP-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "LP")+              }+            , FieldRule::{+              , field = "status"+              , description = Some "Landing-page publication lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues = [ "draft", "live", "retired" ]+              }+            , FieldRule::{+              , field = "slug"+              , description = Some "Producer-owned page route."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "url"+              , description = Some "Published page URL."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Uri+              , when = Some { field = "status", hasValue = [ "live" ] }+              }+            , FieldRule::{+              , field = "liveAt"+              , description = Some "Actual UTC publication time."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Rfc3339Utc+              , when = Some { field = "status", hasValue = [ "live" ] }+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "designRefs"+              , description = Some+                  "Design Brief or Detailed Design URIs for the surface."+              , cardinality = Cardinality.List+              , reference = externalOnly "(BRIEF|DES)"+              }+            , FieldRule::{+              , field = "segmentRefs"+              , description = Some "Segments the page addresses."+              , cardinality = Cardinality.List+              , reference = externalOnly "SEG"+              }+            , FieldRule::{+              , field = "featureRefs"+              , description = Some "Product behavior the page explains."+              , cardinality = Cardinality.List+              , reference = externalOnly "FEAT"+              }+            , FieldRule::{+              , field = "initiativeRef"+              , description = Some "Initiative coordinating the page."+              , cardinality = Cardinality.Scalar+              , reference = externalOnly "INIT"+              }+            , FieldRule::{+              , field = "launchRef"+              , description = Some "Related Launch."+              , cardinality = Cardinality.Scalar+              , reference = Some HandleReferenceRule::{+                , localPrefix = "LAUNCH"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "LAUNCH")+                }+              }+            , FieldRule::{+              , field = "claimRefs"+              , description = Some "Claim Checks for factual copy."+              , cardinality = Cardinality.List+              , reference = externalOnly "CLM"+              }+            ]+          }+        }+      ]+    }
test/fixtures/catalogue/profiles/coordination/package.dhall view
@@ -5,8 +5,43 @@ -- the gap between them. A bug report is the fourth corner: a capability that is -- claimed but does not hold. Behavior that was never provided is an improvement -- request rather than a bug, which is the line that keeps the two apart.-{ bugReports = ./bug-reports.dhall+--+-- Jobs and features give the consumer corner canonical identities. A job+-- states the progress a customer seeks, independent of any solution; a feature+-- is one product behavior with its own delivery lifecycle, reusable across use+-- cases, and linked to the jobs it serves, the capabilities contributing to it,+-- the specifications governing it, and the requests delivering it. A use case+-- remains the scenario that ties them together. The research behind a job's+-- support lives in `documentation.productResearch`.+--+-- Designs carry a surface from why to how before it is built: a Design Brief+-- names the jobs it serves and the scenarios it must work in, a Breadboard+-- names the features its affordances rely on, and a Detailed Design presents+-- it. Implementation stays on those features. `designsFor` builds the profile+-- with a house's closed list of viewer axes; it is a function, not a profile.+--+-- A friction log sits in front of the triangle: an entry records that a+-- surface cost an implementer effort before anyone can say whether it is a+-- defect, a gap, or neither, and its triage status names the bug report or+-- improvement request that took it over.+--+-- A pattern application sits beside them: a service's decision about whether+-- an assessable catalog pattern governs it and which of its own checks prove it.+-- Campaigns coordinate work; audiences describe its consumer populations.+-- Strategy names intended outcomes; launches coordinate publication.+{ strategy = ./strategy.dhall+, launches = ./launches.dhall+, campaigns = ./campaigns.dhall+, audiences = ./audiences.dhall+, bugReports = ./bug-reports.dhall , capabilities = ./capabilities.dhall+, designs = ./designs.dhall+, designsFor = ./designs-for.dhall+, features = ./features.dhall+, frictionLog = ./friction-log.dhall , improvementRequests = ./improvement-requests.dhall+, jobs = ./jobs.dhall+, patternApplications = ./pattern-applications.dhall+, transitions = ./transitions.dhall , useCases = ./use-cases.dhall }
+ test/fixtures/catalogue/profiles/coordination/pattern-applications.dhall view
@@ -0,0 +1,236 @@+--| Profile for a service's decisions about which assessable patterns apply to it.+--+-- ## What a pattern application is+--+-- A catalog maintainer owns an assessable pattern: its stable `PAT-N` handle,+-- its applicability scope, and its criteria (`documentation.patternCatalog`).+-- The service that might adopt it owns the answer to "does this apply to us,+-- and how do we prove it?" A pattern application records that answer as one+-- reviewable document per service and pattern, with a bundle-scoped `PA-N`+-- handle in `applicationId`.+--+-- The `decision` is one of:+--+--   * `applicable` — the service commits to the pattern's criteria. It may bind+--     criterion ids to local, allow-listed check targets in `checks`;+--   * `not-applicable` — the pattern does not govern this service, and the+--     `rationale` says why;+--   * `exception` — the pattern applies but the service is knowingly not+--     meeting it. An `exception` record naming the human authority, the bounded+--     scope, the reason, and the condition that reopens it is then required;+--   * `needs-triage` — nobody has decided yet.+--+-- None of these is conformance. Conformance is evidence about one criterion at+-- an exact service and catalog revision, and it lives outside the document.+-- A scorecard derived from these records must keep `not-applicable`,+-- `exception`, and `needs-triage` apart from a conforming criterion.+--+--+-- ## Checks name local targets, never commands+--+-- A `checks` entry maps a criterion id from the pattern to a target name the+-- service itself defines and allow-lists, such as a Kotei pipeline target. The+-- shared catalog never supplies what runs. Whether every deterministic+-- criterion of an applicable pattern has a binding, and whether a bound id+-- still exists in the pattern, needs both documents, so it belongs to a+-- registry-side projection rather than this profile: a missing binding is an+-- unassessed criterion, not a profile violation.+--+--+-- ## Presence classes+--+-- Nothing is recommended. Per ADR-8 a field is recommended only when a+-- well-run corpus carries it, and a `not-applicable` or `needs-triage` record+-- routinely has no checks and no exception.+--+--+-- ## `legacyTimestamp` is deliberately absent+--+-- This profile is introduced at v0.2 and no v0.1 application corpus exists.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let v02 = ../../Profile/V02.dhall++let scalar =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let list =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.List+        }++let nestedScalar =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++-- Both references are external only: an application lives in the service's+-- repository, while the pattern lives in a catalog elsewhere, so neither can+-- be a local handle. okf requires `localPrefix` to name a prefix this profile+-- declares, so both use `PA`; it is never consulted because `allowLocal` is+-- false. Declaring them as references is also what lets a registry index+-- `service` and `pattern` as typed edges.+let externalOnly =+      \(pattern : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "PA"+          , externalUriSchemes = [ "mori" ]+          , allowLocal = False+          , externalUriPattern = Some pattern+          }++let checks =+      FieldRule::{+      , field = "checks"+      , description = Some+          "Bindings from a pattern criterion id to a check target this service defines and allow-lists. Never a command copied from the catalog."+      , cardinality = Cardinality.List+      , elementFields = Some NestedRules::{+        , required =+          [ nestedScalar+              "criterion"+              "A criterion id declared by the applied pattern."+          , nestedScalar+              "target"+              "The name of a service-owned, allow-listed check target, such as a Kotei pipeline target."+          ]+        , recommended = [] : List NestedFieldRule.Type+        , optional = [] : List NestedFieldRule.Type+        }+      , uniqueBy = Some "criterion"+      }++-- Conditionally required is spelled `required` + `when`: okf rejects a `when`+-- on an optional field.+let exception =+      FieldRule::{+      , field = "exception"+      , description = Some+          "Who accepted not meeting an applicable pattern, over what bounded scope, why, and what reopens the decision. Demanded once `decision` is `exception`."+      , objectFields = Some NestedRules::{+        , required =+          [     nestedScalar+                  "authority"+                  "The human who accepted the exception, as an OKF §7 human actor such as `human:alice`."+            //  { format = Some FieldFormat.HumanActor }+          , nestedScalar+              "scope"+              "Exactly which criteria, components, or situations the exception covers."+          , nestedScalar "reason" "Why the service does not meet the pattern."+          , nestedScalar+              "reviewCondition"+              "The date or event that reopens this decision."+          ]+        , recommended = [] : List NestedFieldRule.Type+        , optional = [] : List NestedFieldRule.Type+        }+      , when = Some { field = "decision", hasValue = [ "exception" ] }+      }++in  Profile::{+    , name = "pattern-applications"+    , description = Some+        "A service's reviewable decisions about which assessable catalog patterns govern it: stable PA handles, the service and pattern as canonical Mori URIs, an applicable / not-applicable / exception / needs-triage decision with rationale, service-owned check bindings, and bounded exceptions. Records applicability, never conformance."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "applicationId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ scalar "type" "The Pattern Application concept type."+        , scalar "title" "Human-readable application title."+        , scalar+            "description"+            "One sentence stating the decision and the pattern it concerns."+        ,     v02.generated+          //  { description = Some+                  "§5.2. Who produced this application's current content, and when."+              }+        ]+      , recommended = [] : List FieldRule.Type+      , optional =+        [ list "tags" "Free classification tags."+        ,     v02.verified+          //  { description = Some+                  "§5.2. Independent confirmations that this decision is accurate."+              }+        ]+      }+    , types =+      [ TypeRule::{+        , type = "Pattern Application"+        , description = Some+            "One service's decision about one assessable catalog pattern."+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "applicationId"+              , description = Some "Bundle-scoped stable PA-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "PA")+              }+            ,     scalar+                    "service"+                    "Canonical Mori project URI of the service this decision governs, such as `mori://acme/billing`."+              //  { reference =+                      externalOnly "mori://[^/]+/[^/]+"+                  }+            ,     scalar+                    "pattern"+                    "Canonical Mori URI of the assessable pattern, such as `mori://acme/patterns/okf/patterns/concepts/PAT-3`."+              //  { reference =+                      externalOnly+                        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/PAT-[1-9][0-9]*"+                  }+            ,     scalar+                    "decision"+                    "Whether the pattern governs this service: `applicable`, `not-applicable`, `exception`, or `needs-triage`."+              //  { allowedValues =+                    [ "applicable", "not-applicable", "exception", "needs-triage" ]+                  }+            , scalar+                "rationale"+                "Why this decision holds for this service."+            , exception+            ]+          , recommended = [] : List FieldRule.Type+          , optional = [ checks ]+          }+        , pathPattern = Some "*"+        , idPrefix = Some "PA"+        }+      ]+    }
+ test/fixtures/catalogue/profiles/coordination/strategy.dhall view
@@ -0,0 +1,440 @@+--| Strategy coordinates intended outcomes and work, beside campaigns and features.+-- Key results reuse job measurement members and store aspirations, not observed+-- current values. Assessments cite Findings or Claim Checks. Strategic Theme is+-- separate from Use Case Theme. No engineering-project, pricing or competitor type+-- is introduced. House status replaces OKF status/staleAfter; no legacyTimestamp.+-- Nothing is recommended: untested drafts legitimately lack reviews and evidence.+-- References crossing profiles are canonical and external-only; local references+-- join the three strategy types. check-gtm.py owns unsupported cross-record checks.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++let externalOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "THEME"+          , allowLocal = False+          , externalUriSchemes = [ "mori" ]+          , externalUriPattern = Some (conceptUri prefix)+          }++let hypothesis = ../../Profile/Hypothesis.dhall++in  Profile::{+    , name = "strategy"+    , description = Some+        "Strategic Themes group time-bounded Objectives and coordinated Initiatives."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "strategyId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ FieldRule::{+          , field = "type"+          , description = Some "The declared concept type."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "title"+          , description = Some "Human-readable concept title."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "description"+          , description = Some "One sentence describing the concept."+          , cardinality = Cardinality.Scalar+          }+        , v02.generated+        ]+      , optional =+        [ FieldRule::{+          , field = "tags"+          , description = Some "Producer-defined search and grouping tags."+          , cardinality = Cardinality.List+          }+        , reviewRule+        , v02.verified+        , v02.sources+        ]+      }+    , types =+      [ TypeRule::{+        , type = "Strategic Theme"+        , description = Some+            "A persistent strategic direction grouping objectives and initiatives."+        , idPrefix = Some "THEME"+        , pathPattern = Some "themes/*"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "strategyId"+              , description = Some "Bundle-scoped stable THEME-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "THEME")+              }+            , FieldRule::{+              , field = "status"+              , description = Some "Strategic theme lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues = [ "active", "retired" ]+              }+            ]+          , optional = [] : List FieldRule.Type+          }+        }+      , TypeRule::{+        , type = "Objective"+        , description = Some+            "A time-bounded intended outcome with explicit key-result targets."+        , idPrefix = Some "OBJ"+        , pathPattern = Some "objectives/*"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "strategyId"+              , description = Some "Bundle-scoped stable OBJ-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "OBJ")+              }+            , FieldRule::{+              , field = "periodStart"+              , description = Some "UTC start of the objective period."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Rfc3339Utc+              }+            , FieldRule::{+              , field = "periodEnd"+              , description = Some "UTC end of the objective period."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Rfc3339Utc+              }+            , FieldRule::{+              , field = "status"+              , description = Some "Objective commitment and result lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues =+                [ "draft", "committed", "achieved", "missed", "dropped" ]+              }+            , FieldRule::{+              , field = "keyResults"+              , description = Some+                  "Objective-local targets; observed values belong in cited evidence."+              , cardinality = Cardinality.List+              , elementFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "id"+                    , description = Some "Objective-local KR-N handle."+                    , cardinality = Cardinality.Scalar+                    , format = Some (FieldFormat.DocumentHandle "KR")+                    }+                  , NestedFieldRule::{+                    , field = "metric"+                    , description = Some "What is measured."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "unit"+                    , description = Some "Unit of the target."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "direction"+                    , description = Some "Desired direction of change."+                    , cardinality = Cardinality.Scalar+                    , allowedValues = [ "increase", "decrease", "maintain" ]+                    }+                  , NestedFieldRule::{+                    , field = "target"+                    , description = Some+                        "Finite numeric aspiration, never an observed value."+                    , cardinality = Cardinality.Scalar+                    }+                  ]+                , optional =+                  [ NestedFieldRule::{+                    , field = "method"+                    , description = Some "How the result will be measured."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "baseline"+                    , description = Some "Finite numeric starting point."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "population"+                    , description = Some "Population the target describes."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "jobRef"+                    , description = Some+                        "Canonical job URI for an outcome pair."+                    , cardinality = Cardinality.Scalar+                    , reference = externalOnly "JOB"+                    }+                  , NestedFieldRule::{+                    , field = "outcomeName"+                    , description = Some+                        "Name of an outcome on the referenced job."+                    , cardinality = Cardinality.Scalar+                    }+                  ]+                }+              , uniqueBy = Some "id"+              }+            , FieldRule::{+              , field = "assessment"+              , description = Some+                  "Evidence-based assessment of the objective result."+              , cardinality = Cardinality.Any+              , when = Some+                { field = "status", hasValue = [ "achieved", "missed" ] }+              , objectFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "rationale"+                    , description = Some+                        "Why the evidence justifies the declared result."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "assessedAt"+                    , description = Some "UTC assessment time."+                    , cardinality = Cardinality.Scalar+                    , format = Some FieldFormat.Rfc3339Utc+                    }+                  , NestedFieldRule::{+                    , field = "evidenceRefs"+                    , description = Some+                        "Canonical Finding or Claim Check URIs."+                    , cardinality = Cardinality.List+                    , reference = externalOnly "(PR|CLM)"+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , FieldRule::{+              , field = "dropReason"+              , description = Some "Why the objective was dropped."+              , cardinality = Cardinality.Scalar+              , when = Some { field = "status", hasValue = [ "dropped" ] }+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "owners"+              , description = Some "Accountable actors."+              , cardinality = Cardinality.List+              , format = Some FieldFormat.Actor+              }+            , FieldRule::{+              , field = "themeRef"+              , description = Some "Strategic Theme for this objective."+              , cardinality = Cardinality.Scalar+              , reference = Some HandleReferenceRule::{+                , localPrefix = "THEME"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "THEME")+                }+              }+            ]+          }+        , guidance = Some+            "Achieved or missed is an author assessment of cited evidence, never inferred from delivery. The opt-in check-gtm.py checks numeric targets, ordered periods and key-result outcome pairs and resolves assessment evidence to Findings or Claim Checks."+        }+      , TypeRule::{+        , type = "Initiative"+        , description = Some+            "Coordinated product, growth, marketing or operations work; not an engineering implementation project."+        , idPrefix = Some "INIT"+        , pathPattern = Some "initiatives/*"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "strategyId"+              , description = Some "Bundle-scoped stable INIT-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "INIT")+              }+            , FieldRule::{+              , field = "kind"+              , description = Some "Kind of coordinated work."+              , cardinality = Cardinality.Scalar+              , allowedValues =+                [ "product", "growth", "marketing", "operations" ]+              }+            , FieldRule::{+              , field = "status"+              , description = Some+                  "Initiative commitment and execution lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues =+                [ "proposed", "committed", "active", "done", "killed" ]+              }+            , FieldRule::{+              , field = "themeRef"+              , description = Some "Strategic Theme guiding this initiative."+              , cardinality = Cardinality.Scalar+              , reference = Some HandleReferenceRule::{+                , localPrefix = "THEME"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "THEME")+                }+              }+            , FieldRule::{+              , field = "killedReason"+              , description = Some "Why the initiative was killed."+              , cardinality = Cardinality.Scalar+              , when = Some { field = "status", hasValue = [ "killed" ] }+              }+            , FieldRule::{+              , field = "outcome"+              , description = Some+                  "What resulted from the completed initiative."+              , cardinality = Cardinality.Scalar+              , when = Some { field = "status", hasValue = [ "done" ] }+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "objectiveRefs"+              , description = Some "Objectives this initiative serves."+              , cardinality = Cardinality.List+              , reference = Some HandleReferenceRule::{+                , localPrefix = "OBJ"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "OBJ")+                }+              }+            , FieldRule::{+              , field = "keyResultRefs"+              , description = Some+                  "Objective-local key results this initiative serves."+              , cardinality = Cardinality.List+              , elementFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "objectiveRef"+                    , description = Some "Objective holding the key result."+                    , cardinality = Cardinality.Scalar+                    , reference = Some HandleReferenceRule::{+                      , localPrefix = "OBJ"+                      , externalUriSchemes = [ "mori" ]+                      , externalUriPattern = Some (conceptUri "OBJ")+                      }+                    }+                  , NestedFieldRule::{+                    , field = "krId"+                    , description = Some "Key-result id on that objective."+                    , cardinality = Cardinality.Scalar+                    , format = Some (FieldFormat.DocumentHandle "KR")+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , hypothesis+            , FieldRule::{+              , field = "studyRef"+              , description = Some "Canonical experiment Study URI."+              , cardinality = Cardinality.Scalar+              , reference = externalOnly "PR"+              }+            , FieldRule::{+              , field = "owners"+              , description = Some "Accountable actors."+              , cardinality = Cardinality.List+              , format = Some FieldFormat.Actor+              }+            , FieldRule::{+              , field = "featureRefs"+              , description = Some "Features contributing product behavior."+              , cardinality = Cardinality.List+              , reference = externalOnly "FEAT"+              }+            , FieldRule::{+              , field = "campaignRefs"+              , description = Some+                  "Campaigns contributing coordinated GTM work."+              , cardinality = Cardinality.List+              , reference = externalOnly "CMP"+              }+            , FieldRule::{+              , field = "segmentRefs"+              , description = Some "Audience Segments served."+              , cardinality = Cardinality.List+              , reference = externalOnly "SEG"+              }+            , FieldRule::{+              , field = "launchRefs"+              , description = Some "Related launches."+              , cardinality = Cardinality.List+              , reference = externalOnly "LAUNCH"+              }+            , FieldRule::{+              , field = "dependsOn"+              , description = Some "Initiatives that must precede this work."+              , cardinality = Cardinality.List+              , reference = Some HandleReferenceRule::{+                , localPrefix = "INIT"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "INIT")+                }+              }+            , FieldRule::{+              , field = "parentInitiativeRef"+              , description = Some "Broader Initiative containing this work."+              , cardinality = Cardinality.Scalar+              , reference = Some HandleReferenceRule::{+                , localPrefix = "INIT"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "INIT")+                }+              }+            , FieldRule::{+              , field = "wave"+              , description = Some "Producer-defined sequencing wave."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "size"+              , description = Some "Producer-defined size estimate."+              , cardinality = Cardinality.Scalar+              }+            ]+          }+        , guidance = Some+            "The opt-in check-gtm.py resolves objective-local key-result ids and requires studyRef to name an experiment Study; initiative delivery does not establish customer outcome."+        }+      ]+    }
+ test/fixtures/catalogue/profiles/coordination/transitions.dhall view
@@ -0,0 +1,349 @@+-- Declared intent only. Observation envelopes and retirement verdicts belong to Mori.+let Profile = ../../Profile/Type.dhall++let Frontmatter = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let F = okf.defaults.FieldRule++let N = okf.defaults.NestedFieldRule++let R = okf.defaults.NestedRules++let C = okf.Cardinality++let Format = okf.FieldFormat++let v02 = ../../Profile/V02.dhall++let reviews = ../../Profile/ReviewRule.dhall++in  Profile::{+    , name = "transitions"+    , description = Some+        "Declared platform responsibility movement with TR-N handles; phase describes intent, never proves predecessor retirement."+    , guidance = Some+        "Use canonical project roots and typed capability/context/flow/use-case URIs. Requirements may be absent or empty. Their environments default to all; acceptance defaults false; itemized defaults true for consumer-migration, event-obligation and responsibility-transfer, otherwise false. Responsibility-transfer is always itemized and has no responsibility field. Mori validates lowercase slugs, fixed maxAge durations, requirements[].owner role/party (a depth-two object), exactly one successor identity, to iff move, cross-list keys, retained duties, environment subsets, registry ownership and reference kinds. The profile engine cannot express these joins, forbidden conditional fields, regexes or recursive owner records. Capability status can raise caution but supplies no retirement evidence. Run mori transitions validate after strict profile enforcement."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "transitionId"+    , frontmatter = Frontmatter::{+      , required =+        [ F::{+          , field = "type"+          , description = Some "Transition concept type."+          , cardinality = C.Scalar+          }+        , F::{+          , field = "title"+          , description = Some "Transition name."+          , cardinality = C.Scalar+          }+        , F::{+          , field = "description"+          , description = Some "One-sentence intent."+          , cardinality = C.Scalar+          }+        , v02.generated+        ]+      , recommended = [ reviews ]+      , optional = [ v02.legacyTimestamp ]+      }+    , types =+      [ TypeRule::{+        , type = "Transition"+        , pathPattern = Some "*"+        , idPrefix = Some "TR"+        , frontmatter = Frontmatter::{+          , required =+            [ F::{+              , field = "transitionId"+              , description = Some "Positive unpadded TR-N handle."+              , cardinality = C.Scalar+              , format = Some (Format.DocumentHandle "TR")+              }+            , F::{+              , field = "coordinator"+              , description = Some "Owning coordinator project root."+              , cardinality = C.Scalar+              , format = Some (Format.UriWithScheme "mori")+              }+            , F::{+              , field = "kind"+              , cardinality = C.Scalar+              , allowedValues =+                [ "split"+                , "absorption"+                , "replacement"+                , "consolidation"+                , "extraction"+                ]+              }+            , F::{+              , field = "phase"+              , cardinality = C.Scalar+              , allowedValues =+                [ "planned"+                , "in-progress"+                , "validating"+                , "complete"+                , "abandoned"+                ]+              }+            , F::{+              , field = "environments"+              , cardinality = C.List+              , description = Some "Nonempty lowercase environment slugs."+              }+            , F::{+              , field = "accountable"+              , description = Some "Accountable parties."+              , cardinality = C.List+              , elementFields = Some R::{+                , required =+                  [ N::{+                    , field = "role"+                    , description = Some "Accountable role."+                    , cardinality = C.Scalar+                    }+                  , N::{+                    , field = "party"+                    , description = Some+                        "Owner identity; unassigned is explicit uncertainty."+                    , cardinality = C.Scalar+                    }+                  ]+                , optional = [] : List N.Type+                }+              }+            , F::{+              , field = "predecessors"+              , description = Some+                  "Services participating before responsibility movement."+              , cardinality = C.List+              , elementFields = Some R::{+                , required =+                  [ N::{+                    , field = "project"+                    , description = Some "Canonical predecessor project root."+                    , cardinality = C.Scalar+                    , format = Some (Format.UriWithScheme "mori")+                    }+                  , N::{+                    , field = "disposition"+                    , description = Some "Retire or retain."+                    , cardinality = C.Scalar+                    , allowedValues = [ "retire", "retain" ]+                    }+                  ]+                , optional = [] : List N.Type+                }+              , uniqueBy = Some "project"+              }+            , F::{+              , field = "successors"+              , description = Some+                  "Known project or explicitly pending identity; exactly one is checked by Mori."+              , cardinality = C.List+              , elementFields = Some R::{+                , required =+                  [ N::{+                    , field = "key"+                    , description = Some "Unique lowercase successor key."+                    , cardinality = C.Scalar+                    }+                  ]+                , optional =+                  [ N::{+                    , field = "project"+                    , description = Some "Canonical successor project root."+                    , cardinality = C.Scalar+                    , format = Some (Format.UriWithScheme "mori")+                    }+                  , N::{+                    , field = "pendingIdentity"+                    , description = Some+                        "Unsettled successor identity; no invented project."+                    , cardinality = C.Scalar+                    }+                  ]+                }+              , uniqueBy = Some "key"+              }+            , F::{+              , field = "responsibilities"+              , description = Some "Declared duties and their dispositions."+              , cardinality = C.List+              , elementFields = Some R::{+                , required =+                  [ N::{+                    , field = "key"+                    , description = Some "Unique lowercase responsibility key."+                    , cardinality = C.Scalar+                    }+                  , N::{+                    , field = "title"+                    , description = Some "Human-readable duty."+                    , cardinality = C.Scalar+                    }+                  , N::{+                    , field = "from"+                    , description = Some "Listed predecessor project root."+                    , cardinality = C.Scalar+                    , format = Some (Format.UriWithScheme "mori")+                    }+                  , N::{+                    , field = "disposition"+                    , description = Some "Move, discontinue or retain."+                    , cardinality = C.Scalar+                    , allowedValues = [ "move", "discontinue", "retain" ]+                    }+                  , N::{+                    , field = "to"+                    , description = Some+                        "Listed successor key, required for move."+                    , cardinality = C.Scalar+                    , when = Some+                      { field = "disposition", hasValue = [ "move" ] }+                    }+                  ]+                , optional =+                  [ N::{+                    , field = "owner"+                    , description = Some "Responsible party."+                    , cardinality = C.Scalar+                    }+                  , N::{+                    , field = "capabilityRefs"+                    , description = Some "Capability concept URIs; read only."+                    , cardinality = C.List+                    , format = Some (Format.UriWithScheme "mori")+                    }+                  , N::{+                    , field = "contextRefs"+                    , description = Some "Typed DDD context URIs."+                    , cardinality = C.List+                    , format = Some (Format.UriWithScheme "mori")+                    }+                  , N::{+                    , field = "flowRefs"+                    , description = Some "Typed DDD flow URIs."+                    , cardinality = C.List+                    , format = Some (Format.UriWithScheme "mori")+                    }+                  , N::{+                    , field = "useCaseRefs"+                    , description = Some "Use Case concept URIs."+                    , cardinality = C.List+                    , format = Some (Format.UriWithScheme "mori")+                    }+                  ]+                }+              , uniqueBy = Some "key"+              }+            ]+          , optional =+            [ F::{+              , field = "phaseSource"+              , description = Some "Source for the declared phase."+              , cardinality = C.Scalar+              }+            , F::{+              , field = "requirements"+              , description = Some+                  "Optional retirement requirements; absence never establishes readiness. Mori validates each owner object."+              , cardinality = C.List+              , elementFields = Some R::{+                , required =+                  [ N::{+                    , field = "key"+                    , description = Some "Unique lowercase requirement key."+                    , cardinality = C.Scalar+                    }+                  , N::{+                    , field = "predecessor"+                    , description = Some "Listed predecessor project root."+                    , cardinality = C.Scalar+                    , format = Some (Format.UriWithScheme "mori")+                    }+                  , N::{+                    , field = "kind"+                    , description = Some "Obligation category."+                    , cardinality = C.Scalar+                    , allowedValues =+                      [ "consumer-migration"+                      , "responsibility-transfer"+                      , "routing-cutover"+                      , "in-flight-drain"+                      , "data-obligation"+                      , "event-obligation"+                      , "rollback"+                      , "operational-continuity"+                      , "ownership"+                      , "other"+                      ]+                    }+                  , N::{+                    , field = "statement"+                    , description = Some "What must be established."+                    , cardinality = C.Scalar+                    }+                  , N::{+                    , field = "minimumBasis"+                    , description = Some "Minimum factual evidence strength."+                    , cardinality = C.Scalar+                    , allowedValues =+                      [ "declared", "source-observed", "runtime-observed" ]+                    }+                  ]+                , optional =+                  [ N::{+                    , field = "owner"+                    , description = Some+                        "Required object with role and party by the Mori gate; nested mappings exceed the profile engine depth."+                    , cardinality = C.Any+                    }+                  , N::{+                    , field = "environments"+                    , description = Some+                        "Subset of transition environments; defaults to all."+                    , cardinality = C.List+                    }+                  , N::{+                    , field = "requiresAcceptance"+                    , description = Some "Defaults to false."+                    , cardinality = C.Scalar+                    , format = Some Format.Boolean+                    }+                  , N::{+                    , field = "itemized"+                    , description = Some+                        "Defaults true for consumer-migration, event-obligation and responsibility-transfer; otherwise false."+                    , cardinality = C.Scalar+                    , format = Some Format.Boolean+                    }+                  , N::{+                    , field = "responsibility"+                    , description = Some+                        "Optional listed duty key; forbidden for responsibility-transfer."+                    , cardinality = C.Scalar+                    }+                  , N::{+                    , field = "maxAge"+                    , description = Some+                        "Owner-selected fixed duration; Mori parses and checks it."+                    , cardinality = C.Scalar+                    }+                  ]+                }+              , uniqueBy = Some "key"+              }+            ]+          }+        }+      ]+    }
test/fixtures/catalogue/profiles/coordination/use-cases.dhall view
@@ -1,4 +1,36 @@ --| Profile for JTBD use cases connected to repository-owned feature work.+--+-- ## Inline records and canonical references+--+-- A use case is a scenario. Its inline `jobs` and `features` records predate+-- the standalone `coordination.jobs` and `coordination.features` profiles and+-- remain valid unchanged. A use case may now link to the canonical concepts:+--+--   * `jobs[].jobRef` names the canonical job an inline job record is a+--     scenario snapshot of, and `jobs[].outcomeNames` names that job's+--     outcomes this scenario is about. The inline record keeps describing this+--     scenario's actor and circumstances; it does not replace the job;+--   * `featureRefs` names standalone features this scenario relies on, and is+--     the preferred representation for new use cases, which then omit inline+--     `features`;+--   * `features[].featureRef` links a retained inline record to a standalone+--     feature during migration. The standalone feature owns the current+--     status, owners, and acceptance; the inline record is a snapshot a UI+--     must not write back.+--+-- Inline `features` is therefore optional rather than required: an early+-- `draft` or `validated` scenario can rely on no feature yet. That a+-- `planned`, `in-progress`, or `delivered` use case names at least one inline+-- feature or `featureRefs` entry is an any-of presence condition okf cannot+-- express, so profile validation checks only the shape of what is present and+-- the opt-in `scripts/check-product-discovery.py` gate enforces readiness,+-- together with name uniqueness, `features[].jobs` resolution, and duplicate+-- canonical references. Existing corpora are not required to run it.+--+-- All three references name concepts in other bundles. okf requires a+-- reference rule's `localPrefix` to be a prefix this profile declares, so they+-- use `UC` with `allowLocal = False` and a JOB-N or FEAT-N+-- `externalUriPattern`. let Profile = ../../Profile/Type.dhall  let FrontmatterRules = ../../Profile/FrontmatterRules.dhall@@ -39,6 +71,20 @@         , cardinality = Cardinality.Scalar         } +let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++let externalOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "UC"+          , externalUriSchemes = [ "mori" ]+          , allowLocal = False+          , externalUriPattern = Some (conceptUri prefix)+          }+ let moriList =       \(name : Text) ->       \(description : Text) ->@@ -64,7 +110,18 @@           , nestedScalar "outcome" "Observable result that satisfies the job."           ]         , recommended = [] : List NestedFieldRule.Type-        , optional = [] : List NestedFieldRule.Type+        , optional =+          [     nestedScalar+                  "jobRef"+                  "Canonical Mori URI of the job this record is a scenario snapshot of."+            //  { reference = externalOnly "JOB" }+          , NestedFieldRule::{+            , field = "outcomeNames"+            , description = Some+                "Names of outcomes on the `jobRef` job that this scenario concerns."+            , cardinality = Cardinality.List+            }+          ]         }       } @@ -104,6 +161,10 @@           , moriList               "improvementRequests"               "Stable Mori concept URIs of repository-owned requests delivering this feature."+          ,     nestedScalar+                  "featureRef"+                  "Canonical Mori URI of the standalone feature this record snapshots."+            //  { reference = externalOnly "FEAT" }           ]         }       }@@ -193,7 +254,6 @@               , format = Some (FieldFormat.UriWithScheme "mori")               }             , jobs-            , features             ]           , recommended =             [ FieldRule::{@@ -204,6 +264,14 @@             ]           , optional =             [ FieldRule::{+              , field = "featureRefs"+              , description = Some+                  "Canonical Mori URIs of standalone features; preferred over inline `features`."+              , cardinality = Cardinality.List+              , reference = externalOnly "FEAT"+              }+            , features+            , FieldRule::{               , field = "improvementRequests"               , description = Some                   "Stable Mori request URIs; mirror the union of feature-level request references."
test/fixtures/catalogue/profiles/documentation/architecture-decisions.dhall view
@@ -11,12 +11,50 @@  let HandleReferenceRule = okf.defaults.HandleReferenceRule +let Nested = okf.defaults.NestedFieldRule+ let Cardinality = okf.Cardinality  let FieldFormat = okf.FieldFormat  let v02 = ../../Profile/V02.dhall +-- `generated` is one mapping (§5.2): who produced the content. A later change+-- that leaves the decision standing, such as marking it superseded, is recorded+-- here instead, so the original author is not overwritten. Rewriting the+-- decision itself updates `generated`.+let amended =+      FieldRule::{+      , field = "amended"+      , description = Some+          "Later changes that leave the decision standing, such as marking it superseded, newest last. `generated` keeps who wrote the decision."+      , cardinality = Cardinality.List+      , elementFields = Some+        { required =+          [ Nested::{+            , field = "by"+            , description = Some+                "§7. The actor responsible: `<producer>/<version>`, `human:<id>`, or `process:<id>`."+            , cardinality = Cardinality.Scalar+            , format = Some FieldFormat.Actor+            }+          , Nested::{+            , field = "at"+            , description = Some "UTC RFC3339 timestamp, ending in `Z`, for when this happened."+            , cardinality = Cardinality.Scalar+            , format = Some FieldFormat.Rfc3339Utc+            }+          , Nested::{+            , field = "change"+            , description = Some "What changed, in one sentence."+            , cardinality = Cardinality.Scalar+            }+          ]+        , recommended = [] : List Nested.Type+        , optional = [] : List Nested.Type+        }+      }+ let scalar =       \(name : Text) ->       \(description : Text) ->@@ -80,6 +118,7 @@         , scalar             "originatingPlan"             "Plan that produced the decision, when recorded."+        , amended         ,     v02.verified           //  { description = Some                   "§5.2. Independent confirmations that this decision record is accurate."
+ test/fixtures/catalogue/profiles/documentation/messaging.dhall view
@@ -0,0 +1,275 @@+--| Messaging is documentation: an explanation to a customer, not another feature,+-- research finding or measurement record. Every factual proof point links a Claim+-- Check or Finding. Audience-any-of and target-type rules run in check-gtm.py.+-- House status replaces OKF status/staleAfter; nothing is recommended because a+-- draft may be unreviewed. Foreign references are canonical and external-only;+-- Positioning references may be local. Matrix coordinates are flat scalar labels.+-- No pricing/offer, competitor or engineering-project type is introduced.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++let externalOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "POS"+          , allowLocal = False+          , externalUriSchemes = [ "mori" ]+          , externalUriPattern = Some (conceptUri prefix)+          }++in  Profile::{+    , name = "messaging"+    , description = Some+        "Positioning and Messages explain value to audiences with attributable proof points."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "messagingId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ FieldRule::{+          , field = "type"+          , description = Some "The declared concept type."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "title"+          , description = Some "Human-readable concept title."+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "description"+          , description = Some "One sentence describing the concept."+          , cardinality = Cardinality.Scalar+          }+        , v02.generated+        ]+      , optional =+        [ FieldRule::{+          , field = "tags"+          , description = Some "Producer-defined search and grouping tags."+          , cardinality = Cardinality.List+          }+        , reviewRule+        , v02.verified+        , v02.sources+        ]+      }+    , types =+      [ TypeRule::{+        , type = "Positioning"+        , description = Some+            "An explanation of differentiated value to a defined audience."+        , idPrefix = Some "POS"+        , pathPattern = Some "positioning/*"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "messagingId"+              , description = Some "Bundle-scoped stable POS-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "POS")+              }+            , FieldRule::{+              , field = "category"+              , description = Some "Category in which the offer is understood."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "problem"+              , description = Some "Customer problem addressed."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "differentiation"+              , description = Some+                  "How this approach differs from alternatives."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "status"+              , description = Some "Positioning lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues = [ "draft", "active", "retired" ]+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "segmentRefs"+              , description = Some "Audience Segments addressed."+              , cardinality = Cardinality.List+              , reference = externalOnly "SEG"+              }+            , FieldRule::{+              , field = "personaRefs"+              , description = Some "Personas addressed."+              , cardinality = Cardinality.List+              , reference = externalOnly "PERSONA"+              }+            , FieldRule::{+              , field = "jobRefs"+              , description = Some "Customer jobs addressed."+              , cardinality = Cardinality.List+              , reference = externalOnly "JOB"+              }+            , FieldRule::{+              , field = "alternatives"+              , description = Some "Alternatives the audience considers."+              , cardinality = Cardinality.List+              }+            , FieldRule::{+              , field = "proofPoints"+              , description = Some "Factual support for value explanations."+              , cardinality = Cardinality.List+              , elementFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "statement"+                    , description = Some "The exact point being supported."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "evidenceRef"+                    , description = Some "Canonical Finding or Claim Check URI."+                    , cardinality = Cardinality.Scalar+                    , reference = externalOnly "(PR|CLM)"+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            ]+          }+        , guidance = Some+            "The opt-in check-gtm.py requires an audience and resolves each proof point to a Finding or Claim Check; a Study is not a finding."+        }+      , TypeRule::{+        , type = "Message"+        , description = Some+            "Content addressed to a customer, relying on cited facts rather than declaring new ones."+        , idPrefix = Some "MSG"+        , pathPattern = Some "messages/*"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "messagingId"+              , description = Some "Bundle-scoped stable MSG-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "MSG")+              }+            , FieldRule::{+              , field = "desiredAction"+              , description = Some "Action the audience is invited to take."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "status"+              , description = Some "Message preparation and use lifecycle."+              , cardinality = Cardinality.Scalar+              , allowedValues = [ "draft", "approved", "in-use", "retired" ]+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "segmentRefs"+              , description = Some "Audience Segments addressed."+              , cardinality = Cardinality.List+              , reference = externalOnly "SEG"+              }+            , FieldRule::{+              , field = "personaRefs"+              , description = Some "Personas addressed."+              , cardinality = Cardinality.List+              , reference = externalOnly "PERSONA"+              }+            , FieldRule::{+              , field = "hook"+              , description = Some "Customer-facing value hook."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "jobRef"+              , description = Some "Canonical job addressed."+              , cardinality = Cardinality.Scalar+              , reference = externalOnly "JOB"+              }+            , FieldRule::{+              , field = "positioningRef"+              , description = Some "Positioning this message expresses."+              , cardinality = Cardinality.Scalar+              , reference = Some HandleReferenceRule::{+                , localPrefix = "POS"+                , externalUriSchemes = [ "mori" ]+                , externalUriPattern = Some (conceptUri "POS")+                }+              }+            , FieldRule::{+              , field = "proofPoints"+              , description = Some "Factual support for value explanations."+              , cardinality = Cardinality.List+              , elementFields = Some NestedRules::{+                , required =+                  [ NestedFieldRule::{+                    , field = "statement"+                    , description = Some "The exact point being supported."+                    , cardinality = Cardinality.Scalar+                    }+                  , NestedFieldRule::{+                    , field = "evidenceRef"+                    , description = Some "Canonical Finding or Claim Check URI."+                    , cardinality = Cardinality.Scalar+                    , reference = externalOnly "(PR|CLM)"+                    }+                  ]+                , optional = [] : List NestedFieldRule.Type+                }+              }+            , FieldRule::{+              , field = "channel"+              , description = Some "Producer-owned delivery channel."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "matrixRow"+              , description = Some "Source matrix row identifier."+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "matrixDimensions"+              , description = Some+                  "Source coordinates retained as scalar labels."+              , cardinality = Cardinality.List+              }+            ]+          }+        , guidance = Some+            "The opt-in check-gtm.py requires an audience and resolves proof-point evidence; approval is an accountable review decision, not inferred from validation."+        }+      ]+    }
test/fixtures/catalogue/profiles/documentation/package.dhall view
@@ -1,6 +1,12 @@ --| Reusable documentation profiles.-{ architectureDecisions = ./architecture-decisions.dhall+-- Messaging explains value to an audience with attributable evidence.+{ messaging = ./messaging.dhall+, architectureDecisions = ./architecture-decisions.dhall , patternCatalog = ./pattern-catalog.dhall+, productResearch = ./product-research.dhall+, runbooks = ./runbooks.dhall , researchDocuments = ./research-documents.dhall+, specifications = ./specifications.dhall+, terminology = ./terminology.dhall , userDocumentation = ./user-documentation.dhall }
test/fixtures/catalogue/profiles/documentation/pattern-catalog.dhall view
@@ -1,4 +1,31 @@ --| Profile for a Mori-addressable catalog of implementation patterns and standards.+--+-- ## Narrative and assessable guidance+--+-- Most catalog documents are narrative: a `Standard` or `Pattern` whose+-- requirements live in prose. Those types carry no handle and gain no new+-- obligation from this profile.+--+-- A maintainer who wants services to report conformance against a document+-- promotes it to `Assessable Standard` or `Assessable Pattern`. Only those two+-- types carry the bundle-scoped `PAT-N` handle in `patternId`, a structured+-- `applicability` scope, and a non-empty list of stable `criteria`. The types+-- are opt-in because okf demands an id from every document of a type that+-- declares an `idPrefix`: putting `PAT` on `Standard` and `Pattern` themselves+-- would break every existing catalog at once.+--+-- A criterion declares the kind of evidence that settles it, never a command.+-- A shared catalog is not authorized to execute code in an adopting service;+-- the service binds criteria to its own allow-listed checks in a+-- `coordination.patternApplications` record. Applicability hints help discover+-- candidate services and never settle applicability: the service's+-- application record does.+--+-- Checks that need more than one document — that every deterministic criterion+-- of an applicable pattern has a check binding, that a retired criterion id is+-- never reused for a new meaning — belong to a registry-side projection, not to+-- the profile. A missing binding is an unassessed criterion, not a profile+-- violation. let Profile = ../../Profile/Type.dhall  let FrontmatterRules = ../../Profile/FrontmatterRules.dhall@@ -13,6 +40,10 @@  let FieldFormat = okf.FieldFormat +let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule+ let v02 = ../../Profile/V02.dhall  let scalar =@@ -24,6 +55,24 @@         , cardinality = Cardinality.Scalar         } +let nestedScalar =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let nestedList =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.List+        }+ let rule =       \(conceptType : Text) ->       \(path : Text) ->@@ -34,6 +83,93 @@         , resourceScheme = Some "mori"         } +-- Whether a candidate service is in scope. `scope` is the human statement;+-- the optional hints are deterministic discovery aids only.+let applicability =+      FieldRule::{+      , field = "applicability"+      , description = Some+          "Where this guidance applies: a human scope statement plus optional deterministic discovery hints. Hints nominate candidate services; a service's pattern application decides."+      , objectFields = Some NestedRules::{+        , required =+          [ nestedScalar+              "scope"+              "The services, components, or situations this guidance governs, in plain language."+          ]+        , recommended = [] : List NestedFieldRule.Type+        , optional =+          [ nestedList+              "projectTypes"+              "Mori project types that are candidates, such as `service` or `library`."+          , nestedList+              "languages"+              "Implementation languages that are candidates, such as `haskell`."+          ,     nestedList+                  "dependenciesAny"+                  "Canonical Mori project URIs; a project depending on any of them is a candidate."+            //  { format = Some (FieldFormat.UriWithScheme "mori") }+          ]+        }+      }++-- One stable, separately reportable requirement. A criterion id is never+-- reused for a different meaning; a changed requirement gets a new id.+let criteria =+      FieldRule::{+      , field = "criteria"+      , description = Some+          "Stable, separately reportable requirements. Each names the kind of evidence that settles it, never a command to run."+      , cardinality = Cardinality.List+      , elementFields = Some NestedRules::{+        , required =+          [ nestedScalar+              "id"+              "Stable document-local criterion id in lowercase-hyphenated form, such as `separate-live-and-ready`. Never reused for a different meaning."+          , nestedScalar+              "statement"+              "The observable requirement a conforming service satisfies."+          ,     nestedScalar+                  "evidenceKind"+                  "What settles the criterion: `test` (an executable test outcome), `report` (a generated machine-readable report), `static-check` (a deterministic analysis), or `review` (human or agent judgment, never a deterministic pass)."+            //  { allowedValues =+                  [ "test", "report", "static-check", "review" ]+                }+          ,     nestedScalar+                  "severity"+                  "`required` for an obligation a conforming service must meet; `advisory` for one it should meet."+            //  { allowedValues = [ "required", "advisory" ] }+          ]+        , recommended = [] : List NestedFieldRule.Type+        , optional = [] : List NestedFieldRule.Type+        }+      , uniqueBy = Some "id"+      }++let assessableRule =+      \(conceptType : Text) ->+      \(description : Text) ->+        TypeRule::{+        , type = conceptType+        , description = Some description+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "patternId"+              , description = Some "Bundle-scoped stable PAT-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "PAT")+              }+            , applicability+            , criteria+            ]+          , recommended = [] : List FieldRule.Type+          , optional = [] : List FieldRule.Type+          }+        , pathPattern = Some "*/**"+        , resourceScheme = Some "mori"+        , idPrefix = Some "PAT"+        }+ in  Profile::{     , name = "mori-documentation-pattern-catalog"     , description = Some@@ -100,12 +236,22 @@       -- ../../Profile/V02.dhall for the policy and its reasoning.       okfVersion = "0.2"     , requireBundleVersion = Some "0.2"+    , -- Only the two assessable types declare an `idPrefix`, so only they are+      -- required to carry `patternId`. A narrative `Standard` or `Pattern`+      -- still validates without one.+      idField = Some "patternId"     , types =       [ rule "Navigation" "getting-started"       , rule "Overview" "*/overview"       , rule "Standard" "*/**"       , rule "Guide" "*/**"       , rule "Pattern" "*/**"+      , assessableRule+          "Assessable Standard"+          "A catalog standard promoted to an assessable contract: stable PAT handle, applicability, and criteria a service can report conformance against."+      , assessableRule+          "Assessable Pattern"+          "A catalog pattern promoted to an assessable contract: stable PAT handle, applicability, and criteria a service can report conformance against."       , rule "Runbook" "*/**"       , rule "Reference" "*/**"       , rule "Gotcha" "*/**"
+ test/fixtures/catalogue/profiles/documentation/product-research.dhall view
@@ -0,0 +1,336 @@+--| Profile for customer and product discovery research with stable PR-N handles.+--+-- ## Product research is not technical research+--+-- `documentation.researchDocuments` records technical investigations about+-- building software: which library, which runtime, which design. This profile+-- records what was learned about customers: who was studied, how, what was+-- observed, and what the authors concluded from it. The two have different+-- lifecycles and different handles (`RES-N` and `PR-N`), and neither is+-- converted into the other.+--+--+-- ## Studies and findings are separate concepts sharing one namespace+--+-- A `Product Research Study` is a bounded research activity: a question, a+-- method, a population, and a context. A `Product Research Finding` is one+-- separately citable result of a study. A finding keeps `observation` (what was+-- seen) apart from `interpretation` (the conclusion drawn), so a reader can+-- disagree with the second without disputing the first.+--+-- Both types use `productResearchId` and the `PR` prefix, so one bundle-wide+-- allocator issues their handles while `type` keeps them distinguishable;+-- `documentation.specifications` is the precedent for two types sharing one+-- prefix. A study stores no list of its findings: that inverse is derived from+-- each finding's `studyRef`.+--+--+-- ## What a finding claims about a job+--+-- `jobAssessments` records whether this finding `supports`, `challenges`, or is+-- `inconclusive` about one named claim concerning one canonical job. It does+-- not decide the job's overall `validationStatus`; the job's own `assessment`+-- does that, citing findings explicitly. `measurements` records observed values+-- of a job's measurable outcome, in that outcome's unit.+--+-- okf can check each member's shape but cannot check that a `value` is a finite+-- number, that `periodStart` precedes `periodEnd`, or that `studyRef` names a+-- study rather than another finding. The opt-in+-- `scripts/check-product-discovery.py` gate checks those, and everything else+-- that needs another concept, until okf and Mori own them.+--+--+-- ## References to other profiles are external only+--+-- Jobs live in a bundle governed by `coordination.jobs`. okf requires a+-- reference rule's `localPrefix` to be an `idPrefix` this profile declares, so+-- job references use `PR` with `allowLocal = False` and a JOB-N+-- `externalUriPattern`. `studyRef` and `supersededBy` may be local, because+-- studies and findings normally share a bundle.+--+--+-- ## Presence classes+--+-- Nothing is recommended (ADR-8): a planned study has no findings, no+-- sources, and no review. `reviews` is optional, as in+-- `documentation.specifications`. Raw material such as interview recordings+-- may live outside the bundle and be cited through `sources`; do not copy+-- sensitive transcripts into a concept.+--+-- No `guidance` is declared (ADR-12).+--+--+-- ## `legacyTimestamp` is deliberately absent+--+-- This profile is introduced at v0.2 and no v0.1 product-research corpus+-- exists.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let scalar =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let nestedScalar =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let conceptUri =+      \(prefix : Text) ->+        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/${prefix}-[1-9][0-9]*"++-- `PR` is the only prefix this profile declares, so it is the `localPrefix` of+-- every reference, including the job references that are never local.+let externalOnly =+      \(prefix : Text) ->+        Some+          HandleReferenceRule::{+          , localPrefix = "PR"+          , externalUriSchemes = [ "mori" ]+          , allowLocal = False+          , externalUriPattern = Some (conceptUri prefix)+          }++let localOrExternalPR =+      Some+        HandleReferenceRule::{+        , localPrefix = "PR"+        , externalUriSchemes = [ "mori" ]+        , allowSelf = False+        , allowLocal = True+        , externalUriPattern = Some (conceptUri "PR")+        }++let rfc3339 =+      \(name : Text) ->+      \(description : Text) ->+        scalar name description // { format = Some FieldFormat.Rfc3339Utc }++let nestedRfc3339 =+      \(name : Text) ->+      \(description : Text) ->+            nestedScalar name description+        //  { format = Some FieldFormat.Rfc3339Utc }++let productResearchId =+      FieldRule::{+      , field = "productResearchId"+      , description = Some "Bundle-scoped stable PR-N handle."+      , cardinality = Cardinality.Scalar+      , format = Some (FieldFormat.DocumentHandle "PR")+      }++let jobRef =+          nestedScalar "jobRef" "Canonical Mori URI of the job concerned."+      //  { reference = externalOnly "JOB" }++let whenStatus =+      \(hasValue : List Text) -> Some { field = "status", hasValue }++let study =+      TypeRule::{+      , type = "Product Research Study"+      , description = Some+          "A bounded customer research activity with a question, method, and population."+      , frontmatter = FrontmatterRules::{+        , required =+          [ productResearchId+          , scalar "question" "What the study set out to learn."+          ,     scalar+                  "method"+                  "How evidence was gathered; explain `mixed` in the body."+            //  { allowedValues =+                  [ "interview"+                  , "observation"+                  , "survey"+                  , "experiment"+                  , "analytics"+                  , "desk-research"+                  , "mixed"+                  ]+                }+          , scalar "population" "Who was studied, and how they were selected."+          , scalar "context" "Circumstances in which the study took place."+          ,     scalar+                  "status"+                  "Study lifecycle: `planned`, `active`, `complete`, or `cancelled`."+            //  { allowedValues = [ "planned", "active", "complete", "cancelled" ] }+          ,     rfc3339 "completedAt" "UTC RFC3339 time the study completed."+            //  { when = whenStatus [ "complete" ] }+          ,     scalar+                  "limitations"+                  "What the study cannot support, such as sampling or method limits."+            //  { when = whenStatus [ "complete" ] }+          ,     scalar "cancellationReason" "Why the study stopped before completing."+            //  { when = whenStatus [ "cancelled" ] }+          ]+        , optional =+          [ FieldRule::{+            , field = "jobRefs"+            , description = Some "Canonical Mori URIs of the jobs this study investigates."+            , cardinality = Cardinality.List+            , reference = externalOnly "JOB"+            }+          , rfc3339 "startedAt" "UTC RFC3339 time the study began."+          ,     v02.sources+            //  { description = Some+                    "§5.1. Protocols, recruiting material, or prior work the study drew on."+                }+          ]+        }+      , pathPattern = Some "*"+      , idPrefix = Some "PR"+      }++let jobAssessments =+      FieldRule::{+      , field = "jobAssessments"+      , description = Some+          "What this finding says about named claims concerning canonical jobs."+      , cardinality = Cardinality.List+      , elementFields = Some NestedRules::{+        , required =+          [ jobRef+          , nestedScalar "claim" "The specific claim about the job being assessed."+          ,     nestedScalar+                  "stance"+                  "`supports`, `challenges`, or `inconclusive` toward the claim."+            //  { allowedValues = [ "supports", "challenges", "inconclusive" ] }+          , nestedScalar "rationale" "Why the observation bears on the claim."+          ]+        , optional =+          [ nestedScalar+              "outcomeName"+              "Name of the job outcome the claim concerns, when it concerns one."+          ]+        }+      }++let measurements =+      FieldRule::{+      , field = "measurements"+      , description = Some+          "Observed values of a job's measurable outcome, in that outcome's unit."+      , cardinality = Cardinality.List+      , elementFields = Some NestedRules::{+        , required =+          [ nestedScalar "name" "Stable measurement name, unique within this finding."+          , jobRef+          , nestedScalar "outcomeName" "Name of the measured outcome on the job."+          , nestedScalar "value" "Observed finite number in `unit`."+          , nestedScalar "unit" "Unit of `value`; the outcome's declared unit."+          , nestedScalar "method" "How the value was obtained."+          , nestedScalar "population" "Whose behavior the value describes."+          , nestedRfc3339 "periodStart" "UTC RFC3339 start of the observed period."+          , nestedRfc3339 "periodEnd" "UTC RFC3339 end of the observed period."+          ]+        }+      , uniqueBy = Some "name"+      }++let finding =+      TypeRule::{+      , type = "Product Research Finding"+      , description = Some+          "One citable observation from a study and the interpretation drawn from it."+      , frontmatter = FrontmatterRules::{+        , required =+          [ productResearchId+          ,     scalar+                  "studyRef"+                  "Local PR-N handle or canonical Mori URI of the study producing this finding."+            //  { reference = localOrExternalPR }+          , scalar "observation" "What was seen or measured, without interpretation."+          , scalar "interpretation" "The conclusion the authors draw from the observation."+          , scalar "context" "Circumstances in which the observation was made."+          , rfc3339 "observedAt" "UTC RFC3339 time the observation was made."+          , scalar "limitations" "What this finding cannot support."+          ,     v02.sources+            //  { description = Some+                    "§5.1. Raw material the observation rests on, possibly outside the bundle."+                }+          ,     scalar+                  "status"+                  "Finding lifecycle: `current`, `superseded`, or `withdrawn`."+            //  { allowedValues = [ "current", "superseded", "withdrawn" ] }+          ,     scalar+                  "supersededBy"+                  "Local PR-N handle or canonical Mori URI of the replacing finding."+            //  { reference = localOrExternalPR, when = whenStatus [ "superseded" ] }+          ,     scalar "withdrawalReason" "Why the finding no longer stands."+            //  { when = whenStatus [ "withdrawn" ] }+          ]+        , optional = [ jobAssessments, measurements ]+        }+      , pathPattern = Some "*"+      , idPrefix = Some "PR"+      }++in  Profile::{+    , name = "product-research"+    , description = Some+        "Customer and product discovery research with stable PR handles: bounded studies, and separately citable findings that keep observation apart from interpretation and assess named claims about canonical jobs. Distinct from technical research documents."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "productResearchId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ scalar+            "type"+            "The Product Research Study or Product Research Finding concept type."+        , scalar "title" "Human-readable title."+        , scalar "description" "One sentence stating the study or finding."+        ,     v02.generated+          //  { description = Some+                  "§5.2. Who produced this document's current content, and when."+              }+        ]+      , optional =+        [ FieldRule::{+          , field = "tags"+          , description = Some "Producer-defined search and grouping tags."+          , cardinality = Cardinality.List+          }+        , reviewRule+        ,     v02.verified+          //  { description = Some+                  "§5.2. Independent confirmations that this document is accurate. Mirror an approving `reviews` entry here."+              }+        ]+      }+    , -- Study and finding `status` are house vocabularies (ADR-1); this profile+      -- does not splice OKF v0.2 §5.4's `status` or `stale_after`.+      types = [ study, finding ]+    }
+ test/fixtures/catalogue/profiles/documentation/runbooks.dhall view
@@ -0,0 +1,121 @@+--| Operational procedures with explicit ownership, applicability and effects.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let v02 = ../../Profile/V02.dhall++let scalar =+      \(field : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let list =+      \(field : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field+        , description = Some description+        , cardinality = Cardinality.List+        }++let reference =+      \(field : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field+        , description = Some description+        , reference = Some HandleReferenceRule::{+          , localPrefix = "RB"+          , externalUriSchemes = [ "mori" ]+          }+        }++in  Profile::{+    , name = "runbooks"+    , description = Some+        "Operational procedures with stable RB handles, accountable ownership, applicability, triggers and declared effects."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "docId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ scalar "type" "The operational document type."+        , scalar "title" "Human-readable procedure title."+        , scalar "description" "Purpose and scope of the procedure."+        ,     scalar "docId" "Bundle-scoped stable RB-N handle."+          //  { format = Some (FieldFormat.DocumentHandle "RB") }+        , scalar+            "owner"+            "Accountable person, team or role that maintains the procedure and receives escalations."+        ,     list+                "projects"+                "Canonical Mori URIs for the projects or artifacts affected by this procedure."+          //  { format = Some (FieldFormat.UriWithScheme "mori") }+        , list+            "environments"+            "Explicit applicable environments; vocabulary is owned by the repository."+        , scalar+            "trigger"+            "Event or symptom that makes this procedure applicable."+        ,     list+                "effects"+                "Possible effects of following the procedure, including conditional branches; this grants no authority."+          //  { allowedValues =+                [ "read-only"+                , "repository-change"+                , "registry-change"+                , "service-change"+                , "data-change"+                ]+              }+        , list "tags" "Search and discovery terms."+        ,     v02.status+          //  { description = Some+                  "Documentation lifecycle: draft, stable or deprecated; this does not certify an operational exercise."+              }+        , v02.generated+        ]+      , recommended = [] : List FieldRule.Type+      , optional =+        [ v02.sources+        , v02.verified+        , v02.staleAfter+        ,     list+                "related"+                "Supporting alerts, dashboards, failure modes or other operational evidence."+          //  { format = Some (FieldFormat.UriWithScheme "mori") }+        ,     reference+                "supersedes"+                "Earlier runbooks replaced by this procedure."+          //  { cardinality = Cardinality.List }+        ,     reference "supersededBy" "Later runbook replacing this procedure."+          //  { cardinality = Cardinality.Scalar }+        ]+      }+    , types =+      [ TypeRule::{+        , type = "Runbook"+        , idPrefix = Some "RB"+        , description = Some+            "An operational procedure whose ordering, prerequisites, verification, stop conditions, recovery and escalation matter."+        }+      ]+    }
+ test/fixtures/catalogue/profiles/documentation/specifications.dhall view
@@ -0,0 +1,230 @@+--| Profile for normative specifications with stable SPEC-N handles.+--+-- A specification states what an owning boundary MUST do. That is what+-- separates this profile from its three documentation siblings, and the+-- separation is the reason it exists rather than being an override on one of+-- them:+--+--   * `architectureDecisions` records a choice and its rationale at a point in+--     time. A decision is finished when it is made; a specification keeps being+--     true, or is superseded.+--   * `researchDocuments` records evidence, alternatives, and conclusions+--     within a bounded question. Research describes what *is*; a specification+--     prescribes what must be.+--   * `userDocumentation` helps a reader accomplish something. A `Reference`+--     page describes an interface as built; a specification binds an+--     implementation that may not exist yet.+--+-- Two fields carry the distinction and neither sibling has anywhere to put+-- them: `specVersion`, the version of the contract that was ratified, and+-- `normativeScope`, which parts of the prose actually bind. Both are demanded+-- on a `Specification` once `status` reaches `ratified`, because a ratified+-- specification that cannot say what binds, at which version, has not been+-- ratified in any usable sense. Before ratification both are optional: a draft+-- legitimately has neither. They are declared on the type rather than+-- profile-wide because they describe the specification text, which a+-- `Specification Pointer` does not carry.+--+-- `normativeScope` lists the binding parts. Anything the document says that is+-- not covered by an entry is informative. There is deliberately no companion+-- list of non-binding sections: a complement is derivable, and two lists can+-- disagree.+--+-- The `Specification Pointer` type covers the common portfolio case where a+-- boundary is accepted in one repository while the authoritative specification+-- lives in the repository that owns it. A pointer is not a weaker+-- specification; it is a specification whose text is elsewhere, and it carries+-- `authoritativeSpec` to say where. Both types share one `SPEC-N` prefix, so a+-- document that is promoted out of a repository — or absorbed back into one —+-- keeps its handle and every durable reference to it. This follows ADR-11's+-- rule that identity is decoupled from classification.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let reviewRule = ../../Profile/ReviewRule.dhall++let v02 = ../../Profile/V02.dhall++let scalar =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let specReference =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , reference = Some HandleReferenceRule::{+          , localPrefix = "SPEC"+          , externalUriSchemes = [ "mori" ]+          }+        }++let ratified = Some { field = "status", hasValue = [ "ratified" ] }++in  Profile::{+    , name = "specifications"+    , description = Some+        "Normative specifications with stable SPEC handles: which boundary is obliged to satisfy the contract, which parts of it bind, at which version, and what proves conformance. The `Specification Pointer` type covers a subject specified authoritatively in another repository."+    , frontmatter = FrontmatterRules::{+      , required =+        [ scalar+            "type"+            "Whether this document is the specification or a pointer to one owned elsewhere."+        , scalar "title" "Human-readable specification title."+        , scalar+            "description"+            "Concise statement of what this specification governs."+        , FieldRule::{+          , field = "specId"+          , description = Some "Bundle-scoped stable SPEC-N handle."+          , cardinality = Cardinality.Scalar+          , format = Some (FieldFormat.DocumentHandle "SPEC")+          }+        , FieldRule::{+          , field = "status"+          , description = Some "Ratification state of the specification."+          , allowedValues =+            [ "draft", "proposed", "ratified", "superseded", "withdrawn" ]+          , cardinality = Cardinality.Scalar+          }+        , -- Deliberately `Uri` and not `UriWithScheme "mori"`. The obliged+          -- boundary is named by whatever canonical identity scheme the+          -- consuming organization uses; `mori://` satisfies this rule without+          -- the profile mandating a particular registry. A list, because one+          -- specification may bind several boundaries at once.+          FieldRule::{+          , field = "owner"+          , description = Some+              "Canonical URI of each boundary obliged to satisfy this specification."+          , cardinality = Cardinality.List+          , format = Some FieldFormat.Uri+          }+        ,     v02.generated+          //  { description = Some+                  "§5.2. Who produced this specification's current content, and when."+              }+        ,     specReference+                "supersededBy"+                "Later specification replacing this one."+          //  { cardinality = Cardinality.Scalar+              , when = Some { field = "status", hasValue = [ "superseded" ] }+              }+        ]+      , -- Nothing is recommended. Under `--strict` a recommended-and-absent+        -- field is an error, and the obvious candidate — `reviews` — fails+        -- ADR-8's test: a draft specification that nobody has reviewed yet is+        -- complete and correct for what it is. Ratification review is recorded+        -- through `reviews` and `verified` when it happens, and demanded by+        -- neither, because a corpus adopting this profile retroactively cannot+        -- truthfully supply review records it never kept.+        recommended = [] : List FieldRule.Type+      , optional =+        [ FieldRule::{+          , field = "conformance"+          , description = Some+              "Versioned contract, fixture package, or suite that proves conformance to this specification."+          , cardinality = Cardinality.List+          , format = Some FieldFormat.Uri+          }+        ,     specReference+                "supersedes"+                "Earlier specifications replaced by this one."+          //  { cardinality = Cardinality.List }+        , -- Coexists with `verified` rather than replacing it; see Policy two+          -- in the header of ../../Profile/V02.dhall.+          reviewRule+        ,     v02.sources+          //  { description = Some+                  "§5.1. Prior art, requirements, and evidence this specification was derived from."+              }+        ,     v02.verified+          //  { description = Some+                  "§5.2. Independent confirmations that this specification is accurate. Mirror approving `reviews` entries here."+              }+        , -- The superseded v0.1 key, kept so an unmigrated corpus keeps+          -- validating. `optional` means its absence is never reported while+          -- its format is still checked whenever it is present.+              v02.legacyTimestamp+          //  { description = Some+                  "Superseded v0.1 revision timestamp. Prefer `generated.at`."+              }+        ]+      }+    , -- The house `status` key above keeps its ratification vocabulary and+      -- deliberately does not adopt OKF v0.2 §5.4's draft/stable/deprecated,+      -- nor `stale_after`. Its allowing `draft` is a coincidence, not partial+      -- conformance: `ratified` is the state OKF has no word for. See the+      -- header of ../../Profile/V02.dhall for the policy and its reasoning.+      okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "specId"+    , types =+      [ TypeRule::{+        , type = "Specification"+        , description = Some+            "A durable statement of required behavior that an owning boundary must satisfy."+        , pathPattern = Some "**"+        , idPrefix = Some "SPEC"+        , -- The two rules that distinguish a specification from a decision+          -- record or a research document, demanded exactly when ratification+          -- makes them answerable. They describe the specification *text*, so+          -- they live on this type rather than profile-wide: a pointer holds no+          -- text to scope or version, and states the version through the+          -- authoritative document it names.+          frontmatter = FrontmatterRules::{+          , required =+            [     scalar+                    "specVersion"+                    "Version of the contract this document ratifies, as implementations cite it."+              //  { when = ratified }+            ,     FieldRule::{+                  , field = "normativeScope"+                  , description = Some+                      "The parts of this document that bind. Anything not named here is informative."+                  , cardinality = Cardinality.List+                  }+              //  { when = ratified }+            ]+          }+        }+      , TypeRule::{+        , type = "Specification Pointer"+        , description = Some+            "A specification whose authoritative text is owned by another repository, recorded here with the ownership it establishes."+        , pathPattern = Some "**"+        , idPrefix = Some "SPEC"+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "authoritativeSpec"+              , description = Some+                  "Canonical URI of the document that authoritatively specifies this subject."+              , cardinality = Cardinality.Scalar+              , format = Some FieldFormat.Uri+              }+            ]+          }+        }+      ]+    }
+ test/fixtures/catalogue/profiles/documentation/terminology.dhall view
@@ -0,0 +1,245 @@+--| Profile for controlled project vocabularies with stable TERM-N handles.+--+-- ## What a term is, and what it is not+--+-- A term defines a word: the canonical spelling a project uses for one concept,+-- a one-sentence definition, the synonyms that mean the same thing, and the+-- wording that must not be used for it. It then points to where the concept's+-- behavior is described or embodied. That pointing is the whole reason the+-- catalog exists as structured data rather than as a glossary page: typed+-- relations, discouraged wording, and code anchors are what an agent or a+-- reviewer can act on.+--+-- A terminology catalog is a controlled vocabulary, not a general ontology or+-- knowledge graph. It does not record:+--+--   * a choice and its rationale — `documentation.architectureDecisions`;+--   * an obligation a boundary must satisfy — `documentation.specifications`;+--   * a reusable solution — `documentation.patternCatalog`;+--   * a provision claim — `coordination.capabilities`;+--   * a page that helps a reader do something — `documentation.userDocumentation`.+--+-- A term links to those from its body or through a `doc` anchor. It never+-- restates them.+--+--+-- ## The house `status` vocabulary+--+-- Per ADR-1, `status` is a house vocabulary, `current` or `deprecated`, and this+-- profile does not splice OKF v0.2 §5.4's `status` or §5.5's `stale_after`.+-- OKF's `draft`/`stable` distinction has no meaning for a word: a term is either+-- the one to use or one that has been retired. A retired term must say what to+-- say instead, so `replacedBy` is demanded once `status` is `deprecated`.+--+--+-- ## Relations+--+-- `broader`, `related`, and `replaces` each accept a local `TERM-N` handle or a+-- canonical `mori://` concept URI, following ADR-11: local references use+-- handles, cross-project references use `mori://`. `sameAs` is external only.+-- An equivalent inside one bundle is an alias, not a second term, so a local+-- `sameAs` is rejected.+--+-- `narrower` is deliberately not a field. A consumer derives it as the inverse+-- of `broader`, so the two directions cannot disagree. There is likewise no+-- body/frontmatter mirror rule: the body should link related terms, but the+-- typed fields already carry the edges, and okf cannot enforce a mirror.+-- Checks that need the whole corpus or the repository — that a reference+-- resolves to a term, that `broader` has no cycle, that `replaces` and+-- `replacedBy` agree, that an anchor exists on disk, that discouraged wording is+-- not another term's name — belong to a repository-local or registry-side gate,+-- not to the profile.+--+--+-- ## Presence classes+--+-- Nothing is recommended. Per ADR-8 a field is recommended only when a well-run+-- corpus carries it, and a well-formed term routinely has no abbreviation, no+-- alias, no discouraged wording, no relation, and no anchor.+--+--+-- ## `legacyTimestamp` is deliberately absent+--+-- This profile is introduced at v0.2 and no v0.1 terminology corpus exists.+let Profile = ../../Profile/Type.dhall++let FrontmatterRules = ../../Profile/FrontmatterRules.dhall++let TypeRule = ../../Profile/TypeRule.dhall++let okf = ../../Profile/okf.dhall++let FieldRule = okf.defaults.FieldRule++let NestedRules = okf.defaults.NestedRules++let NestedFieldRule = okf.defaults.NestedFieldRule++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let v02 = ../../Profile/V02.dhall++let scalar =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let list =+      \(name : Text) ->+      \(description : Text) ->+        FieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.List+        }++let nestedScalar =+      \(name : Text) ->+      \(description : Text) ->+        NestedFieldRule::{+        , field = name+        , description = Some description+        , cardinality = Cardinality.Scalar+        }++let termReference =+      Some+        HandleReferenceRule::{+        , localPrefix = "TERM"+        , externalUriSchemes = [ "mori" ]+        }++let termReferences =+      \(name : Text) ->+      \(description : Text) ->+        list name description // { reference = termReference }++-- `resource` is a plain scalar and deliberately NOT an okf `path` rule, for the+-- same reason as capability evidence: a path rule resolves inside the bundle,+-- and what embodies a term — a module, a source file, a user guide — is almost+-- always outside it. Resolving anchors is a repository-local check.+let anchors =+      FieldRule::{+      , field = "anchors"+      , description = Some+          "What embodies this term: a module, type, function, file, document, or absolute URI a reader can open."+      , cardinality = Cardinality.List+      , elementFields = Some NestedRules::{+        , required =+          [ NestedFieldRule::{+            , field = "kind"+            , description = Some "What sort of artifact this anchor names."+            , allowedValues =+              [ "module", "type", "function", "file", "doc", "uri" ]+            , cardinality = Cardinality.Scalar+            }+          , nestedScalar+              "resource"+              "Module name, qualified identifier, repository-relative path, or absolute URI."+          ]+        , recommended = [] : List NestedFieldRule.Type+        , optional = [ nestedScalar "note" "Why this anchor matters." ]+        }+      }++in  Profile::{+    , name = "terminology"+    , description = Some+        "Controlled project vocabulary with stable TERM handles: the canonical term, a one-sentence definition, accepted and discouraged wording, typed relations to other terms in this or another project, succession, and anchors to what embodies the term. A controlled vocabulary, not a general ontology: decisions, specifications, patterns, capabilities, and guides keep their own profiles."+    , okfVersion = "0.2"+    , requireBundleVersion = Some "0.2"+    , allowUnknownTypes = False+    , idField = Some "termId"+    , frontmatter = FrontmatterRules::{+      , required =+        [ scalar "type" "The Term concept type."+        , scalar+            "title"+            "The canonical term, spelled and cased exactly as it should be written."+        , scalar "description" "A one-sentence definition."+        ,     v02.generated+          //  { description = Some+                  "§5.2. Who produced this term's current content, and when."+              }+        ]+      , recommended = [] : List FieldRule.Type+      , optional =+        [ list "tags" "Free classification tags."+        ,     v02.verified+          //  { description = Some+                  "§5.2. Independent confirmations that this definition is accurate."+              }+        ]+      }+    , types =+      [ TypeRule::{+        , type = "Term"+        , description = Some+            "One concept of this project's vocabulary, under the one name the project uses for it."+        , frontmatter = FrontmatterRules::{+          , required =+            [ FieldRule::{+              , field = "termId"+              , description = Some "Bundle-scoped stable TERM-N handle."+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "TERM")+              }+            , FieldRule::{+              , field = "status"+              , description = Some+                  "Whether this is the term to use or a retired one."+              , allowedValues = [ "current", "deprecated" ]+              , cardinality = Cardinality.Scalar+              }+            , -- Conditionally required is spelled `required` + `when`: okf+              -- rejects a `when` on an optional field.+                  scalar+                    "replacedBy"+                    "The term to use instead. Demanded once `status` is `deprecated`."+              //  { reference = termReference+                  , when = Some { field = "status", hasValue = [ "deprecated" ] }+                  }+            ]+          , optional =+            [ scalar "abbreviation" "An accepted short form of the term."+            , scalar+                "scope"+                "The subsystem or bounded context in which this meaning holds."+            , list "aliases" "Accepted synonyms with identical meaning."+            , list+                "discouraged"+                "Wording that must not be used for this concept. The body says why."+            , termReferences+                "broader"+                "More general terms this term specialises."+            , termReferences+                "related"+                "Associated terms that are neither broader nor equivalent."+            , termReferences "replaces" "Terms this term succeeds."+            ,     list+                    "sameAs"+                    "The same concept published by another project, as canonical Mori term URIs."+              //  { reference = Some HandleReferenceRule::{+                    , localPrefix = "TERM"+                    , externalUriSchemes = [ "mori" ]+                    , allowLocal = False+                    , externalUriPattern = Some+                        "mori://[^/]+/[^/]+/okf/[^/]+/concepts/TERM-[1-9][0-9]*"+                    }+                  }+            , anchors+            ]+          }+        , pathPattern = Some "*"+        , idPrefix = Some "TERM"+        }+      ]+    }
test/fixtures/catalogue/profiles/okf-v0-2.dhall view
@@ -8,8 +8,8 @@ -- Exported from this repository's root package as `okfV02`, so a consumer pins -- it by URL like any other profile in the catalog: -----     let okf = https://raw.githubusercontent.com/shinzui/okf-profiles/v0.8.0/package.dhall---                 sha256:…+--     let okf = https://raw.githubusercontent.com/shinzui/okf-profiles/v0.19.0/package.dhall+--                 sha256:85176d78369b6d73c9f13c30277903b629d6bf048a4c7d71fc26e68b99c3eaa6 -- --     in  okf.okfV02 --
+ test/fixtures/concept-sorting/index.md view
@@ -0,0 +1,8 @@+---+okf_version: "0.2"+---++# Subdirectories++- [requests/](requests/index.md)+
+ test/fixtures/concept-sorting/log.md view
@@ -0,0 +1,5 @@+# Bundle Update Log++## 2026-10-03++* **Addition**: Fixture bundle for ordering concept listings by frontmatter keys.
+ test/fixtures/concept-sorting/requests/a-ten.md view
@@ -0,0 +1,12 @@+---+type: Improvement Request+title: Ten+description: The tenth request, filed first by name, with two tags written out of order.+requestId: IR-10+priority: 2+tags:+  - zeta+  - alpha+---++# Ten
+ test/fixtures/concept-sorting/requests/b-two.md view
@@ -0,0 +1,11 @@+---+type: Improvement Request+title: Two+description: The second request, with the largest priority.+requestId: IR-2+priority: 10+tags:+  - mid+---++# Two
+ test/fixtures/concept-sorting/requests/c-nine.md view
@@ -0,0 +1,9 @@+---+type: Improvement Request+title: Nine+description: The ninth request, with a fractional priority and no tags.+requestId: IR-9+priority: 1.5+---++# Nine
+ test/fixtures/concept-sorting/requests/d-none.md view
@@ -0,0 +1,9 @@+---+type: Improvement Request+title: None+description: A request that has no ID and no priority yet.+tags:+  - beta+---++# None
+ test/fixtures/concept-sorting/requests/e-one.md view
@@ -0,0 +1,9 @@+---+type: Improvement Request+title: One+description: The first request, tied on priority with the tenth.+requestId: IR-1+priority: 2+---++# One
+ test/fixtures/concept-sorting/requests/index.md view
@@ -0,0 +1,8 @@+# Improvement Request++- [Ten](a-ten.md) - The tenth request, filed first by name, with two tags written out of order.+- [Two](b-two.md) - The second request, with the largest priority.+- [Nine](c-nine.md) - The ninth request, with a fractional priority and no tags.+- [None](d-none.md) - A request that has no ID and no priority yet.+- [One](e-one.md) - The first request, tied on priority with the tenth.+
− test/fixtures/profile-discovery/dist-newstyle/valid-build-output.dhall
@@ -1,2 +0,0 @@--- Build-output directories are excluded even when they contain valid profiles.-../../profiles/decisions.dhall
+ test/fixtures/profile-nested-closure-invalid/index.md view
@@ -0,0 +1,6 @@+---+okf_version: "0.2"+---+# Nested closure++- [Note](/note.md)
+ test/fixtures/profile-nested-closure-invalid/log.md view
@@ -0,0 +1,4 @@+# Bundle Update Log++## 2026-10-28+* **Add**: Created nested closure fixture.
+ test/fixtures/profile-nested-closure-invalid/note.md view
@@ -0,0 +1,10 @@+---+type: Note+title: Nested closure+description: A nested closure validation fixture.+generated:+  by: human:fixture-author+rows: [{name: a, stray: x}]+settings: {name: settings, extra: null}+---+# Nested closure
+ test/fixtures/profile-nested-closure-valid/index.md view
@@ -0,0 +1,6 @@+---+okf_version: "0.2"+---+# Nested closure++- [Note](/note.md)
+ test/fixtures/profile-nested-closure-valid/log.md view
@@ -0,0 +1,4 @@+# Bundle Update Log++## 2026-10-28+* **Add**: Created nested closure fixture.
+ test/fixtures/profile-nested-closure-valid/note.md view
@@ -0,0 +1,10 @@+---+type: Note+title: Nested closure+description: A nested closure validation fixture.+generated:+  by: human:fixture-author+rows: [{name: a, note: scoped}]+settings: {name: settings}+---+# Nested closure
+ test/fixtures/profile-product-discovery-invalid/index.md view
@@ -0,0 +1,6 @@+---+okf_version: "0.2"+---+# Product discovery++- [Job](/job.md)
+ test/fixtures/profile-product-discovery-invalid/job.md view
@@ -0,0 +1,25 @@+---+type: Job+title: Author a concept+description: A local product discovery fixture.+generated:+  by: human:fixture-author+status: planned+outcomes:+  - name: Faster+    metric: duration+    unit: seconds+    direction: decrease+    method: observation+    baseline: 0+    population: authors+    period: weekly+    periodStart: 2026-10-01T00:00:00.1Z+    periodEnd: 2026-10-01T00:00:00.2Z+jobs: [{name: 42}]+features: [{name: Editor, featureRef: 'https://example.com/editor', jobs: [Author]}]+featureRefs: ['https://example.com/review']+jobRefs: [JOB-1]+outcomeRefs: [{jobRef: JOB-1, outcomeNames: [Faster]}]+---+# Author a concept
+ test/fixtures/profile-product-discovery-invalid/log.md view
@@ -0,0 +1,4 @@+# Bundle Update Log++## 2026-10-27+* **Add**: Created product discovery fixture.
+ test/fixtures/profile-product-discovery-valid/index.md view
@@ -0,0 +1,6 @@+---+okf_version: "0.2"+---+# Product discovery++- [Job](/job.md)
+ test/fixtures/profile-product-discovery-valid/job.md view
@@ -0,0 +1,26 @@+---+type: Job+title: Author a concept+description: A local product discovery fixture.+generated:+  by: human:fixture-author+status: planned+sources: [interview]+outcomes:+  - name: Faster+    metric: duration+    unit: seconds+    direction: decrease+    method: observation+    baseline: 0+    population: authors+    period: weekly+    periodStart: 2026-10-01T00:00:00.1Z+    periodEnd: 2026-10-01T00:00:00.2Z+jobs: [{name: Author}]+features: [{name: Editor, featureRef: 'https://example.com/editor', jobs: [Author]}]+featureRefs: ['https://example.com/review']+jobRefs: [JOB-1]+outcomeRefs: [{jobRef: JOB-1, outcomeNames: [Faster]}]+---+# Author a concept
+ test/fixtures/profile-product-discovery-valid/log.md view
@@ -0,0 +1,4 @@+# Bundle Update Log++## 2026-10-27+* **Add**: Created product discovery fixture.
test/fixtures/profiles/attested-computation-house.dhall view
@@ -1,26 +1,5 @@--- A *house* profile for the OKF v0.2 attested computation contract--- (specification §10), and the descriptor `docs/user/profiles.md` documents.------ Everything here is a house convention rather than a v0.2 rule. §10.2 marks--- exactly one field REQUIRED for this type, `runtime`, and okf's core already--- reports a missing one under `--strict`. Demanding that every parameter carry--- a `type`, or that an executor name a resource the bundle actually holds, is a--- team's own policy — which is why it lives here and not in--- `docs/profiles/okf-v0-2.dhall`, whose job is the format's own rules.------ This file is exercised by `testFrozenFixturesCompile`, so the descriptor--- `docs/user/profiles.md` shows cannot rot into something that no longer--- compiles.------ Two structural points the prose in that document explains, restated where a--- reader of the descriptor will meet them:------   * The whole contract is scoped to one `type` with a `TypeRule`. Profile---     scope would demand `runtime` of every `Metric` in the bundle.---   * `executor` and `attester` are mappings, so their members are reached with---     `objectFields`, while `parameters` is a list of mappings, so its members---     are reached with `elementFields`. Getting that pair the wrong way round is---     the single easiest mistake to make here.+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let TypeRule = ../../../dhall/defaults/TypeRule.dhall@@ -35,10 +14,6 @@  let nested = ../../../dhall/mk/NestedFieldRule.dhall --- §10.2. A parameter is a named hole an agent may fill. `name` is what the--- computation binds; `type` is what this team insists on so an agent knows what--- kind of value is wanted, and `required` is optional because §10.2 leaves the--- default to the producer. let parameterMembers =       NestedRules::{       , required =@@ -51,10 +26,6 @@       , optional = [ nested.boolean "required" ]       } --- §10.2. The executor names the run instructions and the receipt fields a run--- must return. `bundlePath` checks that the resource names a file the bundle--- actually holds, which is the whole reason a team writes this rule: a contract--- whose executor cannot be found is a contract that cannot be honoured. let executorMembers =       NestedRules::{       , required =@@ -71,8 +42,6 @@         ]       } --- §10.2. The attester is deterministic, no-LLM code that inspects a receipt.--- Same path policy, same reason. let attesterMembers =       NestedRules::{       , required =@@ -88,8 +57,8 @@           "A house convention for the OKF v0.2 attested computation contract."       , guidance = None Text       , okfVersion = "0.2"-      , frontmatter =-        { required = [ field.plain "type" ]+      , frontmatter = FrontmatterDefaults::{+        , required = [ field.plain "type" ]         , recommended = [] : List FieldRule.Type         , optional = [] : List FieldRule.Type         }@@ -102,8 +71,8 @@           , type = "Attested Computation"           , description = Some               "A sanctioned computation, with the means to check that a value came from running it."-          , frontmatter =-            { required =+          , frontmatter = FrontmatterDefaults::{+            , required =               [     field.recordList "parameters" parameterMembers                 //  { description = Some                         "The typed named holes an agent may fill. This team requires at least the declaration, so a computation taking none says so with an empty list."
test/fixtures/profiles/cardinality.dhall view
@@ -1,3 +1,5 @@+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let FieldRule = ../../../dhall/FieldRule.dhall@@ -10,8 +12,8 @@       , description = Some "Exercises scalar and list field cardinality."       , guidance = None Text       , okfVersion = "0.1"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ field.plain "type"           , field.scalar "title"           , field.list "tags"@@ -27,8 +29,8 @@       , types =         [ TypeRule::{           , type = "Cardinality Concept"-          , frontmatter =-            { required = [ field.scalar "score" ]+          , frontmatter = FrontmatterDefaults::{+            , required = [ field.scalar "score" ]             , recommended = [] : List FieldRule             , optional = [] : List FieldRule             }
test/fixtures/profiles/closed-fields.dhall view
@@ -1,3 +1,5 @@+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let TypeRule = ../../../dhall/defaults/TypeRule.dhall@@ -7,11 +9,12 @@ let field = ../../../dhall/mk/FieldRule.dhall  in    { name = "closed-fields"-      , description = Some "Exercises closed field names and value vocabularies."+      , description = Some+          "Exercises closed field names and value vocabularies."       , guidance = None Text       , okfVersion = "0.1"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ field.plain "type"           , field.enum "status" [ "proposed", "accepted", "closed" ]           ]@@ -25,8 +28,8 @@       , types =         [ TypeRule::{           , type = "Improvement Request"-          , frontmatter =-            { required =+          , frontmatter = FrontmatterDefaults::{+            , required =               [ field.enum "status" [ "proposed", "accepted" ]               , field.plain "owner"               ]@@ -36,8 +39,8 @@           }         , TypeRule::{           , type = "Review"-          , frontmatter =-            { required = [ field.plain "reviewer" ]+          , frontmatter = FrontmatterDefaults::{+            , required = [ field.plain "reviewer" ]             , recommended = [] : List FieldRule             , optional = [] : List FieldRule             }
test/fixtures/profiles/concept-filters.dhall view
@@ -1,19 +1,5 @@---| House profile for the concept-filter fixture bundle.------ Mirrors the shape of the improvement-request profile this repository's own--- `docs/improvement-requests/` bundle uses, small enough to reason about and--- resolvable entirely from local relative imports so the test suites stay--- offline.------ Three declarations here carry the weight of the `okf concepts --profile`--- tests. `status` is both an OKF v0.2 core key and a profile-declared closed--- vocabulary, which is what proves a profile rule outranks the core key list.--- `targetPlan` is declared only on `Improvement Request`, which is what proves--- that restricting the check to the types `--type` named is a real restriction.--- `noteKind` is declared plainly profile-wide and closed on `Note` alone, which--- is the shape that catches a check treating the profile-wide rules as a scope--- of their own: there `noteKind` has an empty allowed-value list, and an empty--- list means unconstrained.+let NestedDefaults = ../../../dhall/defaults/NestedRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let FieldRule = ../../../dhall/defaults/FieldRule.dhall@@ -40,7 +26,8 @@         , optional =           [ FieldRule::{             , field = "status"-            , allowedValues = [ "proposed", "accepted", "completed", "rejected" ]+            , allowedValues =+              [ "proposed", "accepted", "completed", "rejected" ]             , cardinality = Cardinality.Scalar             }           , field.documentHandle "requestId" "IR"@@ -49,7 +36,8 @@           , field.rfc3339Utc "completedAt"           , field.record               "generated"-              { required =+              NestedDefaults::{+              , required =                 [ NestedFieldRule::{                   , field = "by"                   , format = Some FieldFormat.Actor@@ -65,7 +53,8 @@               }           , field.recordList               "reviews"-              { required =+              NestedDefaults::{+              , required =                 [ NestedFieldRule::{                   , field = "kind"                   , allowedValues = [ "human", "model" ]
test/fixtures/profiles/conditional-fields-invalid.dhall view
@@ -1,3 +1,5 @@+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let okf = ../../../dhall/package.dhall  let Profile = okf.defaults.Profile@@ -8,8 +10,8 @@  in  Profile::{     , name = "invalid-conditional-fields"-    , frontmatter =-      { required =+    , frontmatter = FrontmatterDefaults::{+      , required =         [ FieldRule::{           , field = "status"           , allowedValues = [ "active" ]
test/fixtures/profiles/conditional-fields.dhall view
@@ -1,3 +1,7 @@+let NestedDefaults = ../../../dhall/defaults/NestedRules.dhall++let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let okf = ../../../dhall/package.dhall  let Profile = okf.defaults.Profile@@ -10,13 +14,14 @@  let Cardinality = okf.Cardinality -let condition = \(field : Text) -> \(hasValue : List Text) -> { field, hasValue }+let condition =+      \(field : Text) -> \(hasValue : List Text) -> { field, hasValue }  let decision =       TypeRule::{       , type = "Decision Record"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ FieldRule::{             , field = "status"             , allowedValues = [ "active", "superseded" ]@@ -36,8 +41,8 @@ let postgresql =       TypeRule::{       , type = "PostgreSQL Derivation"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ FieldRule::{             , field = "derivationKind"             , allowedValues = [ "projection", "operational" ]@@ -63,11 +68,12 @@ let reviewed =       TypeRule::{       , type = "Reviewed Concept"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ okf.mk.FieldRule.recordList               "reviews"-              { required =+              NestedDefaults::{+              , required =                 [ NestedFieldRule::{                   , field = "kind"                   , allowedValues = [ "human", "model" ]@@ -106,8 +112,8 @@ in  Profile::{     , name = "conditional-fields"     , allowUnknownTypes = False-    , frontmatter =-      { required = [ okf.mk.FieldRule.plain "type" ]+    , frontmatter = FrontmatterDefaults::{+      , required = [ okf.mk.FieldRule.plain "type" ]       , recommended = [] : List FieldRule.Type       , optional = [] : List FieldRule.Type       }
test/fixtures/profiles/decisions.dhall view
@@ -1,8 +1,5 @@--- The annotation and TypeRule record completion jointly guard the canonical--- schema, its defaults, and the Haskell decoder against drift. This fixture--- writes its frontmatter with the `mk/FieldRule.dhall` constructors; the--- postgresql fixture writes its own with record completion, so both authoring--- forms stay exercised by the suite.+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let TypeRule = ../../../dhall/defaults/TypeRule.dhall@@ -13,15 +10,16 @@       , description = Some "How this team records architectural decisions."       , guidance = None Text       , okfVersion = "0.1"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ field.documented               "type"               "The OKF concept type; must be a type rule below."           , field.plain "title"           ]         , recommended =-          [ field.documented "status" "One of: proposed, accepted, superseded." ]+          [ field.documented "status" "One of: proposed, accepted, superseded."+          ]         , optional =           [ field.documented               "supersedes"
test/fixtures/profiles/document-references-invalid.dhall view
@@ -1,5 +1,5 @@---| Semantically invalid reference policies; Dhall accepts the shape and--- compileProfile rejects the policy errors before bundle traversal.+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let TypeRule = ../../../dhall/defaults/TypeRule.dhall@@ -25,8 +25,8 @@       , description = None Text       , guidance = None Text       , okfVersion = "0.1"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ rule "badPrefix" "1ADR" ([] : List Text)           , rule "undeclared" "PAT" ([] : List Text)           , rule "badScheme" "ADR" [ "mori_" ]@@ -47,8 +47,8 @@       , types =         [ TypeRule::{           , type = "Decision Record"-          , frontmatter =-            { required = [ rule "conflict" "RFC" ([] : List Text) ]+          , frontmatter = FrontmatterDefaults::{+            , required = [ rule "conflict" "RFC" ([] : List Text) ]             , recommended = [] : List FieldRule.Type             , optional = [] : List FieldRule.Type             }
test/fixtures/profiles/document-references.dhall view
@@ -1,4 +1,5 @@---| Current schema fixture for bundle-local handles and explicit external URIs.+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let TypeRule = ../../../dhall/defaults/TypeRule.dhall@@ -13,14 +14,16 @@  let references =       (field.localOrExternalReference "references" "ADR" [ "mori" ])-        with cardinality = Cardinality.List+      with cardinality = Cardinality.List  let selfReference =       FieldRule::{       , field = "selfReference"       , cardinality = Cardinality.Scalar-      , reference =-          Some HandleReferenceRule::{ localPrefix = "ADR", allowSelf = True }+      , reference = Some HandleReferenceRule::{+        , localPrefix = "ADR"+        , allowSelf = True+        }       }  in    { name = "document-references"@@ -28,8 +31,8 @@           "Architecture decisions with bundle-local or explicitly external references."       , guidance = None Text       , okfVersion = "0.1"-      , frontmatter =-        { required = [ field.plain "type", field.plain "title" ]+      , frontmatter = FrontmatterDefaults::{+        , required = [ field.plain "type", field.plain "title" ]         , recommended = [ references, selfReference ]         , optional = [] : List FieldRule.Type         }
test/fixtures/profiles/formats.dhall view
@@ -1,3 +1,5 @@+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let FieldRule = ../../../dhall/defaults/FieldRule.dhall@@ -14,8 +16,8 @@       , description = Some "Exercises named textual field formats."       , guidance = None Text       , okfVersion = "0.1"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ field.plain "type"           , field.rfc3339Utc "timestamp"           , field.date "published"@@ -37,8 +39,8 @@       , types =         [ TypeRule::{           , type = "Format Concept"-          , frontmatter =-            { required = [ field.uriWithScheme "homepage" "https" ]+          , frontmatter = FrontmatterDefaults::{+            , required = [ field.uriWithScheme "homepage" "https" ]             , recommended = [] : List FieldRule.Type             , optional = [] : List FieldRule.Type             }
test/fixtures/profiles/guidance.dhall view
@@ -1,6 +1,5 @@---| Focused acceptance fixture for profile-wide and type-specific authoring--- guidance. This proves descriptor semantics; it is not a published house QA--- profile.+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let okf = ../../../dhall/package.dhall  let Profile = okf.defaults.Profile@@ -19,8 +18,8 @@         Keep supporting checks in source control and make the observed result reproducible.         ''     , okfVersion = "0.2"-    , frontmatter =-      { required = [ okf.mk.FieldRule.plain "type" ]+    , frontmatter = FrontmatterDefaults::{+      , required = [ okf.mk.FieldRule.plain "type" ]       , recommended = [] : List FieldRule       , optional = [] : List FieldRule       }
+ test/fixtures/profiles/nested-closure-malformed-type.dhall view
@@ -0,0 +1,18 @@+-- Only the type scope carries nested closure; the root flag is historical.+let okf = ../../../dhall/package.dhall++let current = ./nested-closure.dhall++let malformed = okf.defaults.NestedRules::{=} // { allowUnknownFields = "closed" }++in  current //+    { frontmatter = okf.defaults.FrontmatterRules::{=}+    , types =+      [ okf.defaults.TypeRule::{ type = "Note" } //+        { frontmatter = okf.defaults.FrontmatterRules::{=} //+          { required =+            [ okf.defaults.FieldRule::{ field = "settings" } // { objectFields = Some malformed } ]+          }+        }+      ]+    }
+ test/fixtures/profiles/nested-closure-malformed.dhall view
@@ -0,0 +1,13 @@+-- Width extraction could discard this malformed new member and reopen the record.+let okf = ../../../dhall/package.dhall++let current = ./nested-closure.dhall++let malformed = okf.defaults.NestedRules::{=} // { allowUnknownFields = "closed" }++in  current //+    { frontmatter = current.frontmatter //+      { optional =+        [ okf.defaults.FieldRule::{ field = "rows" } // { elementFields = Some malformed } ]+      }+    }
+ test/fixtures/profiles/nested-closure-registry.dhall view
@@ -0,0 +1,1 @@+{ nestedClosure = ./nested-closure.dhall }
+ test/fixtures/profiles/nested-closure.dhall view
@@ -0,0 +1,43 @@+let okf = ../../../dhall/package.dhall++let scalar = \(field : Text) -> okf.defaults.NestedFieldRule::{ field, cardinality = okf.Cardinality.Scalar }++let members = okf.defaults.NestedRules::{+      , allowUnknownFields = False+      , required = [ scalar "name" ]+      , optional =+        [ scalar "start" // { format = Some okf.FieldFormat.Rfc3339Utc }+        , scalar "end" // { format = Some okf.FieldFormat.Rfc3339Utc }+        ]+      , presenceConstraints =+        [ okf.defaults.PresenceConstraint::{+          , whenAnyPresent = [ okf.defaults.ValueSelector::{ field = "start" } ]+          , requireAll = [ okf.defaults.ValueSelector::{ field = "end" } ]+          }+        ]+      , timestampOrderConstraints = [ { before = "start", after = "end" } ]+      }++in  okf.defaults.Profile::{+    , name = "nested-closure"+    , okfVersion = "0.2"+    , frontmatter = okf.defaults.FrontmatterRules::{+      , optional =+        [ okf.defaults.FieldRule::{ field = "rows", elementFields = Some members }+        , okf.defaults.FieldRule::{ field = "settings", objectFields = Some members }+        ]+      }+    , types =+      [ okf.defaults.TypeRule::{+        , type = "Note"+        , frontmatter = okf.defaults.FrontmatterRules::{+          , optional =+            [ okf.defaults.FieldRule::{+              , field = "rows"+              , elementFields = Some okf.defaults.NestedRules::{ optional = [ scalar "note" ] }+              }+            ]+          }+        }+      ]+    }
test/fixtures/profiles/nested-references-and-uniqueness.dhall view
@@ -1,3 +1,7 @@+let NestedDefaults = ../../../dhall/defaults/NestedRules.dhall++let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let FieldRule = ../../../dhall/defaults/FieldRule.dhall@@ -15,7 +19,8 @@ let field = ../../../dhall/mk/FieldRule.dhall  let dependencyRules =-      { required =+      NestedDefaults::{+      , required =         [ NestedFieldRule::{           , field = "ref"           , cardinality = Cardinality.Scalar@@ -33,7 +38,8 @@       }  let acceptanceCriteriaRules =-      { required =+      NestedDefaults::{+      , required =         [ NestedFieldRule::{           , field = "id"           , cardinality = Cardinality.Scalar@@ -50,8 +56,8 @@           "Exercises external-only nested Mori references and list-local acceptance criterion IDs."       , guidance = None Text       , okfVersion = "0.2"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ field.plain "type"           , field.documentHandle "requestId" "IR"           , field.recordList "dependencies" dependencyRules@@ -65,6 +71,7 @@       , allowUnknownFields = True       , idField = Some "requestId"       , requireBundleVersion = None Text-      , types = [ TypeRule::{ type = "Improvement Request", idPrefix = Some "IR" } ]+      , types =+        [ TypeRule::{ type = "Improvement Request", idPrefix = Some "IR" } ]       }     : Profile
test/fixtures/profiles/nested-reviews.dhall view
@@ -1,3 +1,7 @@+let NestedDefaults = ../../../dhall/defaults/NestedRules.dhall++let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let FieldRule = ../../../dhall/defaults/FieldRule.dhall@@ -16,18 +20,22 @@       , description = Some "Validates one level of structured review records."       , guidance = None Text       , okfVersion = "0.1"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ field.plain "type"           , field.recordList               "reviews"-              { required =+              NestedDefaults::{+              , required =                 [ NestedFieldRule::{                   , field = "kind"                   , allowedValues = [ "human", "model" ]                   }-                , NestedFieldRule::{ field = "reviewer", cardinality = Cardinality.Scalar }                 , NestedFieldRule::{+                  , field = "reviewer"+                  , cardinality = Cardinality.Scalar+                  }+                , NestedFieldRule::{                   , field = "reviewed_at"                   , format = Some FieldFormat.Rfc3339Utc                   }@@ -47,12 +55,20 @@                   }                 , NestedFieldRule::{                   , field = "outcome"-                  , allowedValues = [ "approved", "changes-requested", "commented" ]+                  , allowedValues =+                    [ "approved", "changes-requested", "commented" ]                   }-                , NestedFieldRule::{ field = "context", cardinality = Cardinality.Scalar }+                , NestedFieldRule::{+                  , field = "context"+                  , cardinality = Cardinality.Scalar+                  }                 ]               , recommended =-                [ NestedFieldRule::{ field = "notes", cardinality = Cardinality.Scalar } ]+                [ NestedFieldRule::{+                  , field = "notes"+                  , cardinality = Cardinality.Scalar+                  }+                ]               , optional = [] : List NestedFieldRule.Type               }           ]
test/fixtures/profiles/optional-collision-invalid.dhall view
@@ -1,8 +1,5 @@---| One key classified by two presence lists at one scope. The profile cannot--- say both "check for this under --strict" and "never check for this", so--- compileProfile rejects it with ConflictingFieldRequirement rather than picking--- a winner. `reviewedBy` collides at profile scope; `owner` collides at type--- scope.+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let okf = ../../../dhall/package.dhall  let Profile = okf.defaults.Profile@@ -15,16 +12,16 @@  in  Profile::{     , name = "invalid-optional-collisions"-    , frontmatter =-      { required = [ field.plain "type" ]+    , frontmatter = FrontmatterDefaults::{+      , required = [ field.plain "type" ]       , recommended = [ field.plain "reviewedBy" ]       , optional = [ field.plain "reviewedBy" ]       }     , types =       [ TypeRule::{         , type = "Decision Record"-        , frontmatter =-          { required = [ field.plain "owner" ]+        , frontmatter = FrontmatterDefaults::{+          , required = [ field.plain "owner" ]           , recommended = [] : List FieldRule.Type           , optional = [ field.plain "owner" ]           }
test/fixtures/profiles/optional-conditional-invalid.dhall view
@@ -1,8 +1,7 @@---| A condition on an optional rule is dead: `when` gates a presence clause, and--- an optional rule has none. Dhall accepts the shape; compileProfile rejects it--- with OptionalFieldWithCondition before any concept is read.------ The nested declaration is rejected for the same reason at `reviews.model`.+let NestedDefaults = ../../../dhall/defaults/NestedRules.dhall++let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let okf = ../../../dhall/package.dhall  let Profile = okf.defaults.Profile@@ -17,16 +16,16 @@  in  Profile::{     , name = "invalid-optional-conditions"-    , frontmatter =-      { required = [ okf.mk.FieldRule.plain "type" ]+    , frontmatter = FrontmatterDefaults::{+      , required = [ okf.mk.FieldRule.plain "type" ]       , recommended = [] : List FieldRule.Type       , optional = [] : List FieldRule.Type       }     , types =       [ TypeRule::{         , type = "Decision Record"-        , frontmatter =-          { required =+        , frontmatter = FrontmatterDefaults::{+          , required =             [ FieldRule::{               , field = "status"               , allowedValues = [ "accepted", "superseded" ]@@ -35,8 +34,8 @@             , FieldRule::{               , field = "reviews"               , cardinality = Cardinality.List-              , elementFields = Some-                { required =+              , elementFields = Some NestedDefaults::{+                , required =                   [ NestedFieldRule::{                     , field = "kind"                     , allowedValues = [ "human", "model" ]
test/fixtures/profiles/optional-fields.dhall view
@@ -1,15 +1,7 @@---| Exercises the third presence classification end to end.------ `supersedes` and `originatingPlan` are lifecycle and provenance metadata: a--- decision that replaces nothing has no `supersedes` value to give, and not--- every decision came from a plan. They are declared, fully constrained, and--- never reported when absent. `reviewedBy` is a genuine authoring--- recommendation, so `--strict` must still demand it. `supersededBy` shows the--- IR-5 coexistence: a conditional *requirement* in the same type as the optional--- declarations, required only once `status` says the decision was superseded.------ `allowUnknownFields = False` closes the vocabulary, so this fixture also--- proves an optional key counts as declared.+let NestedDefaults = ../../../dhall/defaults/NestedRules.dhall++let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let okf = ../../../dhall/package.dhall  let Profile = okf.defaults.Profile@@ -33,8 +25,8 @@       , type = "Decision Record"       , pathPattern = Some "decisions/*"       , idPrefix = Some "ADR"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ FieldRule::{             , field = "status"             , description = Some "Where the decision is in its lifecycle."@@ -65,10 +57,11 @@             }           , FieldRule::{             , field = "reviews"-            , description = Some "Structured review records, when any were made."+            , description = Some+                "Structured review records, when any were made."             , cardinality = Cardinality.List-            , elementFields = Some-              { required =+            , elementFields = Some NestedDefaults::{+              , required =                 [ NestedFieldRule::{                   , field = "kind"                   , allowedValues = [ "human", "model" ]@@ -96,8 +89,8 @@     , allowUnknownTypes = False     , allowUnknownFields = False     , idField = Some "docId"-    , frontmatter =-      { required = [ field.plain "type", field.plain "title" ]+    , frontmatter = FrontmatterDefaults::{+      , required = [ field.plain "type", field.plain "title" ]       , recommended = [] : List FieldRule.Type       , optional =         [ field.documented
test/fixtures/profiles/postgresql.dhall view
@@ -1,9 +1,5 @@--- The `: Profile` annotation here is load-bearing: it ties this fixture to the--- canonical schema, so the `testLoadProfileFixture` round-trip in test/Main.hs--- fails if okf's published Dhall schema and the Haskell decoder ever drift apart.--- Frontmatter here is written with FieldRule record completion; the decisions--- fixture uses the `mk/FieldRule.dhall` constructors instead, so both authoring--- forms stay exercised.+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let FieldRule = ../../../dhall/defaults/FieldRule.dhall@@ -15,8 +11,8 @@           "Conventions for documenting a PostgreSQL database as an OKF bundle."       , guidance = None Text       , okfVersion = "0.1"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ FieldRule::{             , field = "type"             , description = Some@@ -54,8 +50,8 @@         [ { type = "PostgreSQL Schema"           , description = Some "One namespace grouping tables and views."           , guidance = None Text-          , frontmatter =-            { required = [] : List FieldRule.Type+          , frontmatter = FrontmatterDefaults::{+            , required = [] : List FieldRule.Type             , recommended = [] : List FieldRule.Type             , optional = [] : List FieldRule.Type             }@@ -69,8 +65,8 @@           , description = Some               "One physical table in a schema, including its column list."           , guidance = None Text-          , frontmatter =-            { required = [] : List FieldRule.Type+          , frontmatter = FrontmatterDefaults::{+            , required = [] : List FieldRule.Type             , recommended = [] : List FieldRule.Type             , optional = [] : List FieldRule.Type             }@@ -83,8 +79,8 @@         , { type = "PostgreSQL View"           , description = Some "One view, including the columns it projects."           , guidance = None Text-          , frontmatter =-            { required = [] : List FieldRule.Type+          , frontmatter = FrontmatterDefaults::{+            , required = [] : List FieldRule.Type             , recommended = [] : List FieldRule.Type             , optional = [] : List FieldRule.Type             }
+ test/fixtures/profiles/pre-nested-closure.dhall view
@@ -0,0 +1,182 @@+--| FROZEN: complete descriptor at cfecb72e543c28f5a77ff852445fdd0f256b8810.+-- Every reachable record and union is inline; no live schema imports.+let Cardinality = < Any | Scalar | List >++let FieldFormat =+      < Rfc3339Utc+      | Date+      | Uri+      | UriWithScheme : Text+      | DocumentHandle : Text+      | Actor+      | HumanActor+      | Integer+      | NonNegativeInteger+      | FiniteDecimal+      | Boolean+      >++let FieldCondition = { field : Text, hasValue : List Text }++let HandleReferenceRule =+      { localPrefix : Text+      , externalUriSchemes : List Text+      , allowSelf : Bool+      , allowLocal : Bool+      , externalUriPattern : Optional Text+      }++let PathReferenceRule = { externalUriSchemes : List Text, allowSelf : Bool }++let NestedFieldRule =+      { field : Text+      , description : Optional Text+      , allowedValues : List Text+      , cardinality : Cardinality+      , format : Optional FieldFormat+      , path : Optional PathReferenceRule+      , when : Optional FieldCondition+      , reference : Optional HandleReferenceRule+      }++let ValueSelector = { field : Text, member : Optional Text }++let PresenceConstraint =+      { when : Optional FieldCondition+      , whenAnyPresent : List ValueSelector+      , requireAll : List ValueSelector+      , requireAny : List ValueSelector+      }++let TimestampOrderConstraint = { before : Text, after : Text }++let MembershipConstraint = { source : ValueSelector, target : ValueSelector }++let UniqueValuesConstraint = { selectors : List ValueSelector }++let NestedRules =+      { required : List NestedFieldRule+      , recommended : List NestedFieldRule+      , optional : List NestedFieldRule+      , presenceConstraints : List PresenceConstraint+      , timestampOrderConstraints : List TimestampOrderConstraint+      }++let FieldRule =+      { field : Text+      , description : Optional Text+      , allowedValues : List Text+      , cardinality : Cardinality+      , format : Optional FieldFormat+      , elementFields : Optional NestedRules+      , objectFields : Optional NestedRules+      , reference : Optional HandleReferenceRule+      , path : Optional PathReferenceRule+      , when : Optional FieldCondition+      , uniqueBy : Optional Text+      }++let FrontmatterRules =+      { required : List FieldRule+      , recommended : List FieldRule+      , optional : List FieldRule+      , presenceConstraints : List PresenceConstraint+      , timestampOrderConstraints : List TimestampOrderConstraint+      , membershipConstraints : List MembershipConstraint+      , uniqueValuesConstraints : List UniqueValuesConstraint+      }++let plain =+      \(field : Text) ->+        { field+        , description = None Text+        , allowedValues = [] : List Text+        , cardinality = Cardinality.Any+        , format = None FieldFormat+        , elementFields = None NestedRules+        , objectFields = None NestedRules+        , reference = None HandleReferenceRule+        , path = None PathReferenceRule+        , when = None FieldCondition+        , uniqueBy = None Text+        }++let nestedPlain =+      \(field : Text) ->+        { field+        , description = None Text+        , allowedValues = [] : List Text+        , cardinality = Cardinality.Any+        , format = None FieldFormat+        , path = None PathReferenceRule+        , when = None FieldCondition+        , reference = None HandleReferenceRule+        }++let select = \(field : Text) -> { field, member = None Text }++let scalar = \(field : Text) -> nestedPlain field // { cardinality = Cardinality.Scalar }++let members : NestedRules =+      { required = [ scalar "name" ]+      , recommended = [] : List NestedFieldRule+      , optional =+        [ scalar "start" // { format = Some FieldFormat.Rfc3339Utc }+        , scalar "end" // { format = Some FieldFormat.Rfc3339Utc }+        , scalar "score" // { format = Some FieldFormat.FiniteDecimal }+        ]+      , presenceConstraints =+        [ { when = None FieldCondition+          , whenAnyPresent = [ select "start" ]+          , requireAll = [ select "end" ]+          , requireAny = [] : List ValueSelector+          }+        ]+      , timestampOrderConstraints = [ { before = "start", after = "end" } ]+      }++let fields : FrontmatterRules =+      { required = [] : List FieldRule+      , recommended = [] : List FieldRule+      , optional =+        [ plain "rows" // { elementFields = Some members }+        , plain "settings" // { objectFields = Some members }+        , plain "names" // { cardinality = Cardinality.List }+        , plain "start" // { cardinality = Cardinality.Scalar, format = Some FieldFormat.Rfc3339Utc }+        , plain "end" // { cardinality = Cardinality.Scalar, format = Some FieldFormat.Rfc3339Utc }+        ]+      , presenceConstraints =+        [ { when = None FieldCondition+          , whenAnyPresent = [ select "start" ]+          , requireAll = [ select "end" ]+          , requireAny = [] : List ValueSelector+          }+        ]+      , timestampOrderConstraints = [ { before = "start", after = "end" } ]+      , membershipConstraints =+        [ { source = { field = "rows", member = Some "name" }, target = select "names" } ]+      , uniqueValuesConstraints = [ { selectors = [ select "names", { field = "settings", member = Some "name" } ] } ]+      }++in  { name = "pre-nested-closure"+    , description = Some "The complete descriptor immediately before nested closure."+    , okfVersion = "0.2"+    , guidance = Some "Frozen guidance"+    , frontmatter = fields+    , allowUnknownTypes = False+    , allowUnknownFields = False+    , idField = None Text+    , requireBundleVersion = Some "0.2"+    , types =+      [ { type = "Note"+        , description = None Text+        , guidance = Some "Frozen type guidance"+        , frontmatter = fields+        , pathPattern = None Text+        , resourceScheme = None Text+        , requireSchemaSection = False+        , schemaColumns = [] : List Text+        , idPrefix = None Text+        }+      ]+    }
+ test/fixtures/profiles/pre-product-discovery-0.10.0.0.dhall view
@@ -0,0 +1,177 @@+--| Frozen public descriptor generation from okf-core 0.10.0.0.+-- Every record and union is inline so this fixture cannot silently acquire new+-- members from the live schema. The final value is deliberately unannotated.+-- FROZEN: do not edit after release.+let Cardinality = < Any | Scalar | List >++let FieldFormat =+      < Rfc3339Utc+      | Date+      | Uri+      | UriWithScheme : Text+      | DocumentHandle : Text+      | Actor+      | HumanActor+      | Integer+      | NonNegativeInteger+      | Boolean+      >++let FieldCondition = { field : Text, hasValue : List Text }++let HandleReferenceRule =+      { localPrefix : Text+      , externalUriSchemes : List Text+      , allowSelf : Bool+      , allowLocal : Bool+      , externalUriPattern : Optional Text+      }++let PathReferenceRule = { externalUriSchemes : List Text, allowSelf : Bool }++let NestedFieldRule =+      { field : Text+      , description : Optional Text+      , allowedValues : List Text+      , cardinality : Cardinality+      , format : Optional FieldFormat+      , path : Optional PathReferenceRule+      , when : Optional FieldCondition+      , reference : Optional HandleReferenceRule+      }++let NestedRules =+      { required : List NestedFieldRule+      , recommended : List NestedFieldRule+      , optional : List NestedFieldRule+      }++let FieldRule =+      { field : Text+      , description : Optional Text+      , allowedValues : List Text+      , cardinality : Cardinality+      , format : Optional FieldFormat+      , elementFields : Optional NestedRules+      , objectFields : Optional NestedRules+      , reference : Optional HandleReferenceRule+      , path : Optional PathReferenceRule+      , when : Optional FieldCondition+      , uniqueBy : Optional Text+      }++let FrontmatterRules =+      { required : List FieldRule+      , recommended : List FieldRule+      , optional : List FieldRule+      }++let plain =+      \(field : Text) ->+        { field+        , description = None Text+        , allowedValues = [] : List Text+        , cardinality = Cardinality.Any+        , format = None FieldFormat+        , elementFields = None NestedRules+        , objectFields = None NestedRules+        , reference = None HandleReferenceRule+        , path = None PathReferenceRule+        , when = None FieldCondition+        , uniqueBy = None Text+        }++let nestedPlain =+      \(field : Text) ->+        { field+        , description = None Text+        , allowedValues = [] : List Text+        , cardinality = Cardinality.Any+        , format = None FieldFormat+        , path = None PathReferenceRule+        , when = None FieldCondition+        , reference = None HandleReferenceRule+        }++in  { name = "pre-product-discovery-0.10.0.0"+    , description = Some "The complete public 0.10.0.0 descriptor shape."+    , okfVersion = "0.2"+    , guidance = Some "Frozen guidance"+    , frontmatter =+      { required =+        [ plain "type"+        ,     plain "dependencies"+          //  { cardinality = Cardinality.List+              , elementFields = Some+                { required =+                  [ nestedPlain "id" // { cardinality = Cardinality.Scalar } ]+                , recommended = [] : List NestedFieldRule+                , optional =+                  [     nestedPlain "ref"+                    //  { cardinality = Cardinality.Scalar+                        , reference = Some+                          { localPrefix = "METRIC"+                          , externalUriSchemes = [ "mori" ]+                          , allowSelf = False+                          , allowLocal = False+                          , externalUriPattern = Some "mori://shinzui/.+"+                          }+                        }+                  ]+                }+              , uniqueBy = Some "id"+              }+        ,     plain "generated"+          //  { objectFields = Some+                { required =+                  [     nestedPlain "by"+                    //  { cardinality = Cardinality.Scalar+                        , format = Some FieldFormat.Actor+                        }+                  ,     nestedPlain "at"+                    //  { cardinality = Cardinality.Scalar+                        , format = Some FieldFormat.Rfc3339Utc+                        }+                  ]+                , recommended = [] : List NestedFieldRule+                , optional = [] : List NestedFieldRule+                }+              }+        ]+      , recommended =+        [     plain "usage_count"+          //  { format = Some FieldFormat.NonNegativeInteger }+        ]+      , optional =+        [     plain "resource"+          //  { path = Some+                { externalUriSchemes = [ "https" ], allowSelf = False }+              }+        ]+      }+    , allowUnknownTypes = False+    , allowUnknownFields = True+    , idField = Some "docId"+    , requireBundleVersion = Some "0.2"+    , types =+      [ { type = "Metric"+        , description = Some "A measured quantity."+        , guidance = Some "Frozen guidance"+        , frontmatter =+          { required =+            [     plain "owner"+              //  { cardinality = Cardinality.Scalar+                  , format = Some FieldFormat.HumanActor+                  }+            ]+          , recommended = [] : List FieldRule+          , optional = [] : List FieldRule+          }+        , pathPattern = None Text+        , resourceScheme = None Text+        , requireSchemaSection = False+        , schemaColumns = [] : List Text+        , idPrefix = Some "METRIC"+        }+      ]+    }
+ test/fixtures/profiles/product-discovery-malformed.dhall view
@@ -0,0 +1,2 @@+-- Current-generation members must never disappear through record-width fallback.+./product-discovery.dhall with frontmatter.presenceConstraints = "malformed"
+ test/fixtures/profiles/product-discovery-registry.dhall view
@@ -0,0 +1,1 @@+{ productDiscovery = ./product-discovery.dhall }
+ test/fixtures/profiles/product-discovery.dhall view
@@ -0,0 +1,131 @@+let okf = ../../../dhall/package.dhall++let F = okf.defaults.FieldRule++let N = okf.defaults.NestedFieldRule++let R = okf.defaults.NestedRules++let P = okf.defaults.PresenceConstraint++let s = \(field : Text) -> okf.defaults.ValueSelector::{ field }++let scalar =+      \(field : Text) -> N::{ field, cardinality = okf.Cardinality.Scalar }++let outcomes =+      R::{+      , optional =+        [ scalar "name"+        , scalar "metric"+        , scalar "unit"+        , scalar "direction"+        , scalar "method"+        , scalar "population"+        , scalar "period"+        , scalar "baseline" // { format = Some okf.FieldFormat.FiniteDecimal }+        , scalar "target" // { format = Some okf.FieldFormat.FiniteDecimal }+        , scalar "periodStart" // { format = Some okf.FieldFormat.Rfc3339Utc }+        , scalar "periodEnd" // { format = Some okf.FieldFormat.Rfc3339Utc }+        ]+      , presenceConstraints =+        [ P::{+          , whenAnyPresent =+            [ s "metric"+            , s "unit"+            , s "direction"+            , s "method"+            , s "baseline"+            , s "target"+            , s "population"+            , s "period"+            ]+          , requireAll = [ s "metric", s "unit", s "direction", s "method" ]+          }+        , P::{+          , whenAnyPresent = [ s "baseline" ]+          , requireAll = [ s "population", s "period" ]+          }+        ]+      , timestampOrderConstraints =+        [ { before = "periodStart", after = "periodEnd" } ]+      }++let jobs = R::{ required = [ scalar "name" ] }++let features =+      R::{+      , optional =+        [ scalar "name"+        , scalar "featureRef"+        , N::{ field = "jobs", cardinality = okf.Cardinality.List }+        ]+      }++let links =+      R::{+      , optional =+        [ scalar "jobRef"+        , N::{ field = "outcomeNames", cardinality = okf.Cardinality.List }+        ]+      , presenceConstraints =+        [ P::{+          , whenAnyPresent = [ s "outcomeNames" ]+          , requireAll = [ s "jobRef" ]+          }+        ]+      }++in  okf.defaults.Profile::{+    , name = "product-discovery"+    , okfVersion = "0.2"+    , frontmatter = okf.defaults.FrontmatterRules::{+      , optional =+        [ F::{ field = "outcomes", elementFields = Some outcomes }+        , F::{ field = "sources", cardinality = okf.Cardinality.List }+        , F::{+          , field = "status"+          , cardinality = okf.Cardinality.Scalar+          , allowedValues = [ "draft", "planned", "in-progress", "delivered" ]+          }+        , F::{+          , field = "jobs"+          , elementFields = Some jobs+          , uniqueBy = Some "name"+          }+        , F::{ field = "jobRefs", cardinality = okf.Cardinality.List }+        , F::{ field = "features", elementFields = Some features }+        , F::{ field = "featureRefs", cardinality = okf.Cardinality.List }+        , F::{ field = "outcomeRefs", elementFields = Some links }+        ]+      , presenceConstraints =+        [ P::{+          , whenAnyPresent =+            [ { field = "outcomes", member = Some "baseline" } ]+          , requireAll = [ s "sources" ]+          }+        , P::{+          , when = Some+            { field = "status"+            , hasValue = [ "planned", "in-progress", "delivered" ]+            }+          , requireAny = [ s "features", s "featureRefs" ]+          }+        ]+      , membershipConstraints =+        [ { source = { field = "outcomeRefs", member = Some "jobRef" }+          , target = s "jobRefs"+          }+        , { source = { field = "features", member = Some "jobs" }+          , target = { field = "jobs", member = Some "name" }+          }+        ]+      , uniqueValuesConstraints =+        [ { selectors =+            [ s "featureRefs"+            , { field = "features", member = Some "featureRef" }+            ]+          }+        ]+      }+    }
test/fixtures/profiles/type-frontmatter.dhall view
@@ -1,3 +1,5 @@+let FrontmatterDefaults = ../../../dhall/defaults/FrontmatterRules.dhall+ let Profile = ../../../dhall/Profile.dhall  let TypeRule = ../../../dhall/defaults/TypeRule.dhall@@ -7,11 +9,12 @@ let FieldRule = ../../../dhall/FieldRule.dhall  in    { name = "type-frontmatter"-      , description = Some "Exercises profile-wide and type-specific field rules."+      , description = Some+          "Exercises profile-wide and type-specific field rules."       , guidance = None Text       , okfVersion = "0.1"-      , frontmatter =-        { required =+      , frontmatter = FrontmatterDefaults::{+        , required =           [ field.plain "type"           , field.documented "title" "Human-readable concept title."           ]@@ -25,11 +28,14 @@       , types =         [ TypeRule::{           , type = "Owned Concept"-          , frontmatter =-            { required =+          , frontmatter = FrontmatterDefaults::{+            , required =               [ field.documented "owner" "Person responsible for the concept." ]             , recommended =-              [ field.documented "reviewer" "Person who independently reviewed it." ]+              [ field.documented+                  "reviewer"+                  "Person who independently reviewed it."+              ]             , optional = [] : List FieldRule             }           }
+ test/fixtures/sweep/accept/log.md view
@@ -0,0 +1,4 @@+# Bundle Update Log++## 2026-10-28+* **Add**: Created the sweep fixture.
+ test/fixtures/sweep/accept/notes/first.md view
@@ -0,0 +1,11 @@+---+type: Note+title: First+description: A note in the sweep fixture.+timestamp: "2026-10-01T00:00:00Z"+status: final+---++# First++A note.
+ test/fixtures/sweep/cases/expected.json view
@@ -0,0 +1,4 @@+{+  "note-missing-title": "title",+  "note-bad-status": "status"+}
+ test/fixtures/sweep/cases/note-bad-status/notes/bad-status.md view
@@ -0,0 +1,11 @@+---+type: Note+title: Bad status+description: A note in the sweep fixture.+timestamp: "2026-10-01T00:00:00Z"+status: wip+---++# Bad status++A note.
+ test/fixtures/sweep/cases/note-missing-title/notes/missing-title.md view
@@ -0,0 +1,10 @@+---+type: Note+description: A note in the sweep fixture.+timestamp: "2026-10-01T00:00:00Z"+status: draft+---++# x++A note.
+ test/fixtures/sweep/classification.dhall view
@@ -0,0 +1,76 @@+-- Exercises every classification rule of okf profile sweep that an open+-- profile can reach: a vocabulary a condition depends on (admitValue), a+-- local-only reference whose allowLocal is masked (covered by reference), an+-- allowSelf that is never read (inert), an unconstrained optional field+-- (inert), and an untested vocabulary (unprotected or a manifest exception).+let okf = ../../../dhall/package.dhall++let Profile = okf.defaults.Profile++let TypeRule = okf.defaults.TypeRule++let FieldRule = okf.defaults.FieldRule++let FrontmatterDefaults = okf.defaults.FrontmatterRules++let HandleReferenceRule = okf.defaults.HandleReferenceRule++let Cardinality = okf.Cardinality++let FieldFormat = okf.FieldFormat++let field = okf.mk.FieldRule++in  Profile::{+    , name = "sweep-classification"+    , allowUnknownTypes = False+    , idField = Some "docId"+    , frontmatter = FrontmatterDefaults::{+      , required = [ field.plain "type", field.plain "title" ]+      }+    , types =+      [ TypeRule::{+        , type = "Task"+        , idPrefix = Some "TASK"+        , frontmatter = FrontmatterDefaults::{+          , required =+            [ FieldRule::{+              , field = "docId"+              , cardinality = Cardinality.Scalar+              , format = Some (FieldFormat.DocumentHandle "TASK")+              }+            , FieldRule::{+              , field = "status"+              , allowedValues = [ "open", "done" ]+              , cardinality = Cardinality.Scalar+              }+            , FieldRule::{+              , field = "closedBy"+              , cardinality = Cardinality.Scalar+              , when = Some { field = "status", hasValue = [ "done" ] }+              }+            ]+          , optional =+            [ FieldRule::{+              , field = "parent"+              , cardinality = Cardinality.Scalar+              , reference = Some HandleReferenceRule::{+                , localPrefix = "TASK"+                , externalUriSchemes = [ "https" ]+                , allowLocal = False+                }+              }+            , FieldRule::{+              , field = "note"+              , description = Some "Free text; checked by nothing."+              }+            , FieldRule::{+              , field = "priority"+              , allowedValues = [ "low", "high" ]+              , cardinality = Cardinality.Scalar+              }+            ]+          }+        }+      ]+    }
+ test/fixtures/sweep/closed.dhall view
@@ -0,0 +1,35 @@+-- A closed profile: deleting a declaration makes an accepted key unknown, which+-- the acceptance bundle notices for the wrong reason.+let okf = ../../../dhall/package.dhall++let Profile = okf.defaults.Profile++let FieldRule = okf.defaults.FieldRule++let FrontmatterDefaults = okf.defaults.FrontmatterRules++let Cardinality = okf.Cardinality++let field = okf.mk.FieldRule++in  Profile::{+    , name = "sweep-closed"+    , allowUnknownFields = False+    , frontmatter = FrontmatterDefaults::{+      , required = [ field.plain "type", field.plain "title" ]+      , optional =+        [ field.plain "description"+        , field.plain "timestamp"+        , FieldRule::{+          , field = "size"+          , allowedValues = [ "s", "m" ]+          , cardinality = Cardinality.Scalar+          }+        , FieldRule::{+          , field = "colour"+          , allowedValues = [ "red", "blue" ]+          , cardinality = Cardinality.Scalar+          }+        ]+      }+    }
+ test/fixtures/sweep/profile.dhall view
@@ -0,0 +1,39 @@+-- The smallest suite a load-bearing sweep can disagree with: two cases that+-- each notice some relaxations, and rules (type, summary) that no case tests.+let okf = ../../../dhall/package.dhall++let Profile = okf.defaults.Profile++let TypeRule = okf.defaults.TypeRule++let FieldRule = okf.defaults.FieldRule++let FrontmatterDefaults = okf.defaults.FrontmatterRules++let Cardinality = okf.Cardinality++let field = okf.mk.FieldRule++in  Profile::{+    , name = "sweep"+    , description = Some "A two-case suite for okf profile sweep."+    , allowUnknownTypes = False+    , frontmatter = FrontmatterDefaults::{+      , required = [ field.plain "type", field.plain "title" ]+      }+    , types =+      [ TypeRule::{+        , type = "Note"+        , frontmatter = FrontmatterDefaults::{+          , required =+            [ FieldRule::{+              , field = "status"+              , allowedValues = [ "draft", "final" ]+              , cardinality = Cardinality.Scalar+              }+            ]+          , optional = [ field.plain "summary" ]+          }+        }+      ]+    }