okf-cli 0.13.0.0 → 0.14.0.0
raw patch · 11 files changed
+512/−398 lines, 11 filesdep ~okf-corePVP ok
version bump matches the API change (PVP)
Dependency ranges changed: okf-core
API changes (from Hackage documentation)
+ Okf.Cli: [current] :: ConceptsOptions -> !Bool
+ Okf.Cli: computationReportWith :: VersionDeclaration -> BundleInventory -> [Concept] -> [Text]
- Okf.Cli: ConceptsOptions :: !Maybe FilePath -> ![Text] -> ![WhereCondition] -> ![FieldSelector] -> ![FieldSelector] -> ![Text] -> ![SortKey] -> !Maybe FilePath -> !Bool -> ConceptsOptions
+ Okf.Cli: ConceptsOptions :: !Maybe FilePath -> ![Text] -> ![WhereCondition] -> ![FieldSelector] -> ![FieldSelector] -> ![Text] -> ![SortKey] -> !Maybe FilePath -> !Bool -> !Bool -> ConceptsOptions
Files
- CHANGELOG.md +26/−0
- help/computations.md +24/−78
- help/concepts.md +12/−0
- help/format.md +18/−14
- help/graph.md +4/−2
- help/index.md +4/−4
- help/trust.md +21/−46
- help/validation.md +21/−46
- okf-cli.cabal +3/−3
- src/Okf/Cli.hs +180/−173
- test/Main.hs +199/−32
CHANGELOG.md view
@@ -7,6 +7,32 @@ ## [Unreleased] +## [0.14.0.0] - 2026-12-02++### Added++- Recognize OKF format 0.3, with a worked bundle and reference profile in the+ repository.+- `concepts --current` selects stable concepts and follows deprecated concepts'+ replacement paths.++### Changed++- **Breaking (library).** `ConceptsOptions` adds a `current` field.+- Require `okf-core ^>=0.14.0.0` for OKF 0.3 support.+- `trust` and `show` distinguish current verification from historical+ reviews. Freshness checks accept timestamps as well as dates.+- `computations` reports structural eligibility. `show --computation` selects+ a declared source file ahead of an inline fence.+- Graphs include links from the format's path fields.+- Plain validation reports and skips untyped Markdown and tolerates dangling+ links. Strict mode checks links. An enforced profile can diagnose a missing+ type on an untyped record carrying its document ID.++### Fixed++- Index writes preserve complete root frontmatter.+ ## [0.13.0.0] - 2026-11-08 ### Added
help/computations.md view
@@ -1,92 +1,38 @@-ATTESTED COMPUTATIONS ON THE COMMAND LINE--A concept whose type is exactly "Attested Computation" carries a sanctioned way-to compute a value, so a consumer can confirm a number came from running the-blessed computation rather than from an agent improvising its own query. See-"okf help format" for the frontmatter contract; this topic is the tooling.--LISTING A BUNDLE'S COMPUTATIONS+ATTESTED COMPUTATION DEFINITIONS okf computations BUNDLE - One aligned row per computation, ordered by concept ID:-- computations/order-total postgres order_id (uuid, required) inline executor + attester-- The five columns are the concept ID, the runtime, the parameters, where the- computation lives, and which of the two run-and-check halves the concept- declares. Every one restates frontmatter and nothing else.-- Selection is on the type value being exactly "Attested Computation". A Metric- that happens to carry a runtime key does not appear, and a computation- declaring no contract field at all still does.-- A bundle with no attested computations prints nothing and exits 0. An empty- report is not an error.--WHAT THE PARENTHESISED CELLS MEAN-- An absent value prints as a phrase rather than as an empty cell, so the report- hides nothing that okf validate --strict would report:-- computations/margin (no runtime) year (integer, required) inline (neither)- computations/no-computation bigquery (no parameters) (no computation) (neither)- computations/two-blocks bigquery (no parameters) (2 computations) (neither)-- (no runtime) The one field the specification marks REQUIRED for this- type is missing.- (no computation) and (2 computations) are the two ways the exactly-one rule- breaks: a computation is either one code block under- "# Computation" or a computation path, never both, never- neither.- (neither) The concept names no executor and no attester. Legitimate:- section 10.2 marks neither half REQUIRED. The column reads- "executor + attester", "executor", "attester", or- "(neither)", and all four are conformant.+ The report lists concepts of type Attested Computation by ID. It shows the+ runtime, parameters, selected source, declared executor and attester, and+ any missing parts. An eligible definition has a runtime, an attester+ resource and a usable computation source. A run needs its own verdict. - A parameter with no declared type prints as its bare name.+ Parameters require a name and type. Required defaults to false. Common+ types include string, integer, number, boolean, date and timestamp.+ Runtimes can add their own types, such as uuid. -PRINTING ONE COMPUTATION+INSPECTING THE SANCTIONED SOURCE okf show BUNDLE CONCEPT_ID --computation - Prints the computation and nothing else -- no metadata, no heading, no body- prose:-- SELECT SUM(quantity * unit_amount_minor) AS total_minor- FROM order_lines- WHERE order_id = :order_id-- The flag prints either form. When the concept names a file with the- computation key, okf resolves the path against the bundle and prints the- file's contents, so a caller never has to know which form the producer chose.-- A concept offering no computation, or more than one, exits non-zero with a- message on stderr rather than guessing which to print. The flag works with- interactive selection and resolves a document ID by the same rules as show- without it.--WHAT okf DOES NOT DO+ A computation path selects a file in the bundle. A missing or unusable+ file produces a diagnostic. When the field is absent or empty, show prints+ the first fenced block in the ATX Computation section. A heading at the+ same level or above ends that section. - okf never executes a computation and never attests one. Printing one is not- executing it, and no column of okf computations says whether a computation- would attest cleanly -- none can. A receipt is what a run returns and a- verdict is what an attester produces from it; both are runtime artifacts that- live outside the bundle.+ Strict validation flags definitions that offer both a file and an inline+ fence or that contain extra qualifying fences. - "executor + attester" means the concept names the two things a consumer would- need in order to run and check it, not that either has ever been run.+RUNTIME EVIDENCE - The trust and staleness reported by okf trust are a different question again:- they say whether the DEFINITION still matches policy, which a computation can- pass while any individual run fails, and the reverse.+ An agent supplies values for the declared parameters. The runtime binds+ those values to the sanctioned source and records the executed artifact+ in a receipt. An attester checks that receipt and returns a boolean ok+ plus an optional reason. Consumers surface failed verdicts and withhold+ the value. Those artifacts belong to the run. okf inspects definitions. SEE ALSO - okf help format The contract keys and the exactly-one rule.- okf help validation Which computation problems --strict reports.- okf help trust Trust tiers, staleness, and recorded provenance.- okf help concepts The unrestricted listing, filterable by any key. Where- this report is fixed to one type and five columns,- `okf concepts --type 'Attested Computation' --show- runtime` asks the same question with columns you pick.+ okf help format The contract fields and bundle conventions.+ okf help validation Strict authoring checks for computation sources.+ okf help trust Verification and freshness of a definition.
help/concepts.md view
@@ -195,6 +195,18 @@ The profile is used for nothing else here. okf concepts never reports a bundle deviation; that is okf validate --profile's job. +CURRENT KNOWLEDGE++ okf concepts BUNDLE --current++ Filters select the initial concepts. The current view displays stable+ results once each and follows superseded_by on matching deprecated concepts.+ It reports missing or cyclic replacement references. Ordinary --where+ queries can still select the status values used by a house profile.++ When moving a concept, leave a short deprecated concept at the old path and+ set superseded_by to the new concept. The old identifier stays inspectable.+ JSON OUTPUT okf concepts BUNDLE --json | jq '.[] | select(.status == "draft")'
help/format.md view
@@ -1,8 +1,9 @@ OKF BUNDLE FORMAT An OKF bundle is a directory tree of Markdown files. The directory structure is-up to the producer; it need not mirror any domain taxonomy. Every Markdown file-whose name is not reserved is a concept document.+up to the producer; it need not mirror any domain taxonomy. A non-reserved .md file+with a nonempty string type is a concept. Untyped Markdown is skipped.+Dot-paths and descendant symlinks stay outside the inventory. RESERVED FILES @@ -41,20 +42,21 @@ description Recommended. One-sentence summary used in indexes and graphs. resource Optional. Canonical URI for the underlying asset (absent for purely abstract concepts).- tags Optional. List of short categorization strings.+ tags Optional. One tag or a list of tags. - These OKF v0.2 families are all optional, and okf reads every one:+ These OKF families are all optional, and okf reads every one: generated Who produced this content and when: a mapping with a REQUIRED "by" actor and an optional "at" timestamp. verified Independent confirmation that the content is accurate: a mapping, or a list of them. Distinct from generated -- who wrote a concept need not be who confirmed it.- status Lifecycle state: draft, stable, deprecated, or superseded.+ status Lifecycle state: draft, stable, or deprecated. Absence means stable.- stale_after Calendar date after which the content should be re-confirmed.+ superseded_by Bundle path to the replacement for a deprecated concept.+ stale_after RFC 3339 instant or UTC date when review becomes due. Advisory; okf reports it but never refuses a stale concept.- sources What the content was derived from, one entry per source, with+ sources What the content was derived from, as one mapping or a list, with optional credibility signals such as author and usage_count. usage_window The period those sources were observed over. @@ -62,10 +64,11 @@ and falls back to it, but new documents should write generated. Producers may add any other keys; the parser preserves unknown keys as- extension data and never rejects a document for carrying them.+ extension data. Use x-<producer>-<name> for reserved extension keys. A bundle may declare its format version in the root index.md frontmatter as- okf_version: "0.2". An undeclared bundle is read with v0.1 fallbacks.+ okf_version: "0.3". The root can also carry title, description, license and+ extensions. Undeclared and older bundles have legacy fallbacks. ATTESTED COMPUTATIONS @@ -78,11 +81,11 @@ therefore what a parameter means -- a SQL bind variable, a dbt var, a Python argument. parameters The typed named holes an agent may fill, each with a name and- optionally a type and whether it is required.+ runtime type. Required defaults to false. computation A path to a file holding the computation, used instead of an- inline block.+ inline block. When both are present, the file wins. executor Run instructions plus the receipt fields a run must return.- attester Deterministic, no-LLM code that inspects a receipt and+ attester REQUIRED. Deterministic, no-LLM code that inspects a receipt and returns a verdict. The computation is provided in exactly one of two ways: a single code block@@ -95,7 +98,7 @@ okf never executes a computation and never attests one. A receipt and a verdict are runtime artifacts that live outside the bundle; okf records the computation and the means to check it, and stops there. Use okf computations- to list a bundle's computations and okf show CONCEPT --computation to print+ to list a bundle's computations and okf show BUNDLE CONCEPT --computation to print one, in whichever of the two forms its producer chose. CONVENTIONAL BODY HEADINGS@@ -109,7 +112,8 @@ # Citations is the superseded v0.1 heading for external sources backing claims in the body; v0.2 records those in the sources frontmatter family and- cites them from the body with Markdown footnotes.+ cites them from the body with Markdown footnotes. okf preserves old+ Citations sections verbatim as body Markdown. THE references/ CONVENTION
help/graph.md view
@@ -31,13 +31,15 @@ WHAT BECOMES AN EDGE - A Markdown link to a .md concept that exists in the bundle. Nothing else:+ Body links and supported path fields become edges when they resolve to an+ existing concept. This includes resource, sources[].resource, superseded_by,+ computation, executor.resource and attester.resource. - External URLs are never edges. - Links to non-.md files -- a computation, an executor script under references/ -- are never edges. - A dangling link to a concept that does not exist is ignored here, though- okf validate reports it. See "okf help validation".+ okf validate --strict reports it. See "okf help validation". Edges are untyped. A link asserts that two concepts are related; the kind of relationship is conveyed by the surrounding prose, not by the graph.
help/index.md view
@@ -6,13 +6,13 @@ okf index BUNDLE Preview every generated index. okf index BUNDLE --write Write them into the bundle.- okf index BUNDLE --write --okf-version 0.2 Also declare the OKF version.+ okf index BUNDLE --write --okf-version 0.3 Also declare the OKF version. Without --write nothing is modified: each generated index prints to stdout. WHAT A GENERATED INDEX CONTAINS - Three sections, in this order, each omitted when it would be empty:+ Sections, in this order, when they contain entries: # Subdirectories Immediate subdirectories, one bullet each. # Files Immediate non-Markdown files, one bullet each.@@ -33,7 +33,7 @@ THE VERSION DECLARATION --okf-version MAJOR.MINOR declares that version in the bundle root index's- frontmatter as okf_version, overriding any existing declaration.+ frontmatter as okf_version. All other root metadata is preserved. Without the flag, an existing declaration is preserved and an absent one stays absent: regenerating indexes never destroys a bundle's declared version@@ -46,7 +46,7 @@ --write replaces the BODY of every index.md in the bundle, which is what it is for. Point it at a bundle whose index files someone wrote by hand and that- prose is gone; only the version declaration is carried across.+ prose is replaced. The complete root YAML header is carried across. Because generation is deterministic and never reads the clock, committing the result and running
help/trust.md view
@@ -1,60 +1,34 @@ TRUST, STALENESS, AND PROVENANCE -Two commands report what a bundle says about how far its content can be-trusted. Neither stores anything: every value is derived from frontmatter on-each run, and nothing is read that the bundle does not say.- REPORTING TRUST TIERS okf trust BUNDLE - One aligned row per concept, ordered by concept ID:-- aggregates/invoice human-reviewed stable ok- aggregates/order machine-confirmed stable ok- commands/issue-invoice unverified stable ok- mappings/ordering-to-billing machine-confirmed stable stale since 2026-07-01- policies/reserve-stock unverified draft ok-- The four columns are the concept ID, the derived trust tier, the status- field, and staleness. The ID column is padded to the longest ID in the- bundle, so the width shifts when a bundle gains a deeper concept.--TIERS+ The report shows each concept's ID, current trust tier, lifecycle status and+ freshness. - unverified The concept declares no verified entry.- machine-confirmed Verified, but every verified[].by is a non-human actor.- human-reviewed Some verified[].by uses the human: prefix.+ unverified No current verification covers this content.+ machine-confirmed Current verification comes from non-human actors.+ human-reviewed A current verification comes from a human: actor. - The prefix is the only thing separating the last two. The tier comes from- verified, never from generated: who wrote a concept need not be who confirmed- it.+ A verification covers content when its at is at or after generated.at. With+ no generation record, every usable event can qualify. If a known generator+ lacks a usable change time, okf reports the uncertainty and assigns+ unverified. Earlier events remain visible through okf show. STATUS AND STALENESS - status shows stable for a concept that declares none, because an absent- status means stable. The other values are draft, deprecated, and superseded.-- This is the one column okf derives rather than restates, so it is the one- place this report and `okf concepts` disagree on purpose. `okf concepts- --where status=stable` selects only the concepts whose frontmatter actually- says stable; the ones that say nothing appear here as stable and there not at- all. Ask this command for the derived reading and that one for what is- written down.-- The staleness column reads "ok" both for a concept with no stale_after and- for one whose deadline has not arrived -- okf does not claim a concept is- fresh, only that nothing says otherwise. A passed deadline prints- "stale since DATE", and a stale_after that is not a YYYY-MM-DD date prints- "unparseable stale_after VALUE" rather than being silently treated as fresh.+ An empty or absent status means stable. The standard values are stable,+ draft and deprecated. Other values are displayed as written. Use+ okf concepts BUNDLE --current for a stable view with replacement links. - Staleness is computed against today, so this command's output changes with- the date even when the bundle does not. It is advisory: okf never refuses a- stale concept.+ A deadline is stale at the specified instant or later. A date alone means+ midnight UTC. The report shows "no review deadline" when stale_after is+ absent or empty, and names malformed values when it cannot parse them.+ Staleness signals that content needs another check. - Staleness here is not the log staleness okf validate and okf log- --check-stale report. That one compares a concept's generated date against- the nearest log.md; this one reads the concept's own stale_after deadline.+ Log staleness compares the UTC calendar day of the content change with the+ nearest log.md. The trust report uses the concept's stale_after deadline. LISTING RECORDED PROVENANCE @@ -86,8 +60,9 @@ with no id prints "(no id)" in the label column, because an id is optional and matters only when the body cites the entry with a footnote. - A source's resource is deliberately never path-checked: it names either a- followable artifact or a scope descriptor such as "all queries in project X".+ A source resource can name a followable artifact or a scope descriptor such+ as "all queries in project X". A resolvable reference can contribute a graph+ relationship. SEE ALSO
help/validation.md view
@@ -8,9 +8,8 @@ PERMISSIVE VS STRICT - Default (permissive) validation requires each concept to have a non-empty- type frontmatter field, and checks that values it can read have the right- shape -- that tags is a list of strings, for instance.+ Default validation accepts typed concepts, skips untyped Markdown with an+ advisory, and tolerates broken links. Invalid YAML still fails validation. --strict additionally requires the recommended authoring fields: @@ -18,14 +17,14 @@ description generated (or the superseded v0.1 timestamp it falls back to) - and reports authoring problems in the optional OKF v0.2 families a document+ and reports authoring problems in the optional OKF families a document has actually used: generated must carry a by actor a sources entry is missing its resource two sources entries share an id a body footnote label names no sources entry, or the reverse- a superseded v0.1 field in a bundle that declares okf_version 0.2+ a superseded v0.1 field in a bundle that declares okf_version 0.2 or higher a path in a frontmatter value names a file the bundle does not hold and, for a concept whose type is exactly "Attested Computation":@@ -39,28 +38,15 @@ REFERENTIAL INTEGRITY - Validation also checks the whole bundle, not just single files:-- - A Markdown link to another .md concept that does not exist in the- bundle is a dangling reference and fails validation.- - Duplicate concept IDs are reported.- - Present log.md files must use valid YYYY-MM-DD headings and non-empty- date groups.- - External URLs and non-.md links are not checked.-- These checks run in both permissive and strict modes.+ Both modes diagnose duplicate concept IDs and malformed log date groups. - A path held in a frontmatter value -- resource, computation,- executor.resource, attester.resource -- is resolved too, but only under- --strict, and only the top-level resource plus the three attested- computation fields. A sources entry's resource is deliberately not- path-checked: it names either a followable artifact or a scope descriptor- such as "all queries in project X", so treating it as a path would report- correct bundles as broken.+ Strict validation checks broken body links and unresolved path fields+ including resource, superseded_by, computation, executor.resource and+ attester.resource. Source scopes can be descriptive text. - A relative path resolves against the concept's own directory. A path that- fails to resolve but would have resolved from the bundle root says so, and- names the leading-slash spelling to write instead.+ Bare paths resolve against the concept's directory. An older bundle or one+ without a declaration can retry a path field at the root. A v0.3 path field+ explicitly starts at the root when it has a leading slash. LOG ADVISORIES @@ -78,39 +64,28 @@ CONFORMANCE VS AUTHORING CHECKS - OKF conformance itself is permissive. It requires only parseable frontmatter- with a non-empty type field, and it tells consumers to TOLERATE broken links- (a link to a not-yet-written concept is not malformed) and NOT to reject a- bundle for a missing optional field or an unrecognized type value.-- That is why every check on an optional v0.2 family lives under --strict,- including the ones the specification marks REQUIRED "for this type". Marking- runtime REQUIRED for an Attested Computation binds the producer; it does not- license a consumer to refuse the bundle. okf validate is an authoring-time- linter, so it goes further than conformance on purpose -- treat these as- authoring aids, not as a gate on what consumers will accept.+ Only a nonempty type is required for a concept. Optional fields, unknown+ types and extension keys are compatible with core conformance. - A team that wants any of them enforced writes a house profile, which okf- can then check and, with --profile-enforce, fail on. See- "okf help profiles".+ An explicitly selected profile can apply additional rules. An untyped+ Markdown record carrying the profile's document ID is checked when that+ profile requires type. Profile diagnostics are advisory until+ --profile-enforce is supplied. See "okf help profiles". VERSION DECLARATION A bundle may declare its format version in its root index.md frontmatter: - okf_version: "0.2"+ okf_version: "0.3" - An undeclared bundle is read with v0.1 fallbacks and is never penalized for- it. Declaring 0.2 is an opt-in to the stricter reading: after that, a- superseded v0.1 field such as timestamp is reported under --strict, because- a bundle that says it targets v0.2 is describing an authoring mistake rather- than exercising a compatibility path.+ Older and undeclared bundles remain readable. Strict mode diagnoses legacy+ fields superseded by the declared version and warns on unknown versions. OUTPUT A valid bundle prints a concept count and exits 0: - OK: 4 concepts (okf_version 0.2)+ OK: 3 concepts (okf_version 0.3) An invalid bundle prints deterministic errors to stderr and exits non-zero, for example:
okf-cli.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.4 name: okf-cli-version: 0.13.0.0+version: 0.14.0.0 synopsis: Command-line interface for Open Knowledge Format bundles description: okf-cli provides the @okf@ executable for working with Open Knowledge Format@@ -81,7 +81,7 @@ generic-lens >=2.2 && <2.4, githash ^>=0.1, lens ^>=5.3,- okf-core ^>=0.13.0.0,+ okf-core ^>=0.14.0.0, optparse-applicative >=0.19 && <0.20, process >=1.6 && <1.7, terminal-size >=0.3.4 && <0.4,@@ -107,7 +107,7 @@ generic-lens >=2.2 && <2.4, lens ^>=5.3, okf-cli,- okf-core ^>=0.13.0.0,+ okf-core ^>=0.14.0.0, optparse-applicative >=0.19, process >=1.6 && <1.7, temporary,
src/Okf/Cli.hs view
@@ -34,6 +34,7 @@ ValidateOptions (..), bundleListJson, computationReport,+ computationReportWith, conceptReport, conceptReportJson, conceptsProfileDiagnostics,@@ -73,7 +74,7 @@ import Data.ByteString.Lazy qualified as LazyBytes import Data.ByteString.Lazy.Char8 qualified as LazyByteString import Data.Char (isDigit)-import Data.Foldable (toList, traverse_)+import Data.Foldable (for_, toList, traverse_) import Data.Generics.Labels () import Data.List qualified as List import Data.List.NonEmpty qualified as NonEmpty@@ -86,6 +87,7 @@ import Data.Time (defaultTimeLocale, formatTime, getCurrentTime, utctDay) import Okf.Actor (parseActor, renderActor) import Okf.Bundle+import Okf.BundlePath (requireBundlePath) import Okf.Cli.Agent.Config ( AgentCommandName (..), AgentField (..),@@ -129,10 +131,10 @@ import Okf.Cli.ProfileSweep (ProfileSweepOptions (..), profileSweepOptionsParser, runProfileSweep) import Okf.Cli.ProfileSweep qualified as Sweep import Okf.Cli.Version (appVersionWithGit)+import Okf.Computation import Okf.ConceptId import Okf.Document ( Attester (..),- ComputationSource (..), DocumentParseError (..), Executor (..), Frontmatter (..),@@ -144,12 +146,14 @@ attestedComputationType, body, effectiveUsageWindow,+ hasFrontmatterFence, renderStatus, )-import Okf.Graph (buildGraph)+import Okf.Graph (buildGraphWith) import Okf.Index+import Okf.Lifecycle (ReplacementIssue (..), currentKnowledge) import Okf.Log qualified as Log-import Okf.Path (PathReference (..), classifyPathReference)+import Okf.Path (PathResolution (..)) -- 'List' and 'Object' are 'Okf.Profile.Cardinality' constructors here; aeson's -- same-named 'Value' constructors are reached as 'Aeson.Object' and friends.@@ -188,7 +192,8 @@ renderDocumentId, renderValueSelector, validateProfileVersion,- validateProfileWith,+ validateProfileWithDeclaration,+ validateUntypedProfileRecords, ) import Okf.Profile.Bootstrap import Okf.Profile.Discovery (loadProfileDescriptorWithoutNetwork)@@ -241,10 +246,12 @@ ) import Okf.Trust ( Staleness (..),+ VerificationSummary (..), latestVerification, renderStaleness, renderTrustTier,- staleness,+ stalenessAt,+ summarizeVerification, trustTier, ) import Okf.Validation@@ -371,7 +378,8 @@ showFields :: ![Text], sortKeys :: ![SortKey], profilePath :: !(Maybe FilePath),- json :: !Bool+ json :: !Bool,+ current :: !Bool } deriving stock (Show, Eq) @@ -988,6 +996,7 @@ ) ) <*> jsonSwitch+ <*> switch (long "current" <> help "Select stable knowledge and follow deprecated replacement paths") where fieldSelectorReader = eitherReader (first (Text.unpack . renderFilterParseError) . parseFieldSelector . Text.pack)@@ -1842,7 +1851,8 @@ exists <- bootstrapEntryExists destination directory <- doesDirectoryExist destination when (exists && not directory) $ dieText (Text.pack destination <> " is not a directory")- declaration <- readBundleVersion destination >>= either (dieText . renderBundleError) pure+ metadata <- readBundleMetadata destination >>= either (dieText . renderBundleError) pure+ let declaration = maybe VersionUndeclared bundleVersion metadata version <- case declaration of VersionDeclared declaredVersion -> pure (Just declaredVersion) VersionUndeclared -> pure Nothing@@ -2013,6 +2023,7 @@ -- regenerating into a directory that declares a version cannot strip it. writeProfileDocumentation :: Maybe OkfVersion -> FilePath -> [Concept] -> IO () writeProfileDocumentation versionOverride destination concepts = do+ void (readBundleMetadata destination >>= either (dieText . renderBundleError) pure) -- A destination that does not exist yet walks as an IO error, which here -- means "no pre-existing concepts" rather than a failure: writeBundle -- creates the directory.@@ -2028,9 +2039,7 @@ indexes <- renderBundleIndexesWith versionOverride destination indexCount <- case indexes of Left bundleError -> dieText (renderBundleError bundleError)- -- Count distinct paths: 'renderBundleIndexes' yields the bundle root twice,- -- once as "" and once as ".", which write the same file.- Right rendered -> pure (length (List.nub (map (FilePath.normalise . fst) rendered)))+ Right rendered -> pure (length rendered) written <- writeBundleIndexesWith versionOverride destination case written of Left bundleError -> dieText (renderBundleError bundleError)@@ -2232,12 +2241,19 @@ if pickProfile then Just <$> resolveProfilePath Nothing else traverse (resolveProfilePath . Just) profilePath- concepts <- loadBundleOrExit resolvedBundle+ (concepts, untyped) <- walkBundleDocuments resolvedBundle >>= either (dieText . renderBundleError) pure inventory <- loadBundleInventoryOrExit resolvedBundle logs <- loadLogsOrExit resolvedBundle declaration <- loadBundleVersionOrExit resolvedBundle+ indexProblems <- checkBundleIndexes resolvedBundle declaration inventory+ mapM_ (Text.IO.hPutStrLn stderr . renderBundleError) indexProblems+ for_ untyped $ \record ->+ Text.IO.hPutStrLn stderr (Text.pack (untypedSourcePath record) <> ": skipped Markdown without a nonempty type") let coreProfile = if strictMode then StrictAuthoring else PermissiveConformance coreErrors = validateBundle coreProfile declaration inventory concepts <> validateBundleLogs logs+ unless strictMode $ for_ concepts $ \concept ->+ for_ (optionalFamilyProblems (conceptDocument concept)) $ \problem ->+ Text.IO.hPutStrLn stderr ("warning: " <> renderBundleValidationError (DocumentInvalid (conceptIdOf concept) problem)) mapM_ (Text.IO.hPutStrLn stderr . renderBundleValidationError) coreErrors let logStalenessReport = logStaleness concepts logs@@ -2256,11 +2272,12 @@ -- profile demands is context for every line below it. let violations = validateProfileVersion declaration compiled- <> validateProfileWith inventory coreProfile compiled concepts+ <> validateProfileWithDeclaration declaration inventory coreProfile compiled concepts+ <> validateUntypedProfileRecords compiled untyped mapM_ (Text.IO.hPutStrLn stderr . ("profile: " <>) . renderProfileViolation compiled concepts) violations pure violations - let coreFailed = any bundleValidationErrorIsFailure coreErrors+ let coreFailed = not (null indexProblems) || any bundleValidationErrorIsFailure coreErrors profileFailed = profileEnforce && not (null profileViolations) logFailed = logEnforce && (any bundleValidationErrorIsAdvisory coreErrors || not (null logStalenessReport)) if coreFailed || profileFailed || logFailed@@ -2330,8 +2347,9 @@ runLogAdd bundlePath LogAddOptions {conceptId, kind, message, date, preview = previewOnly} = do entryDate <- maybe todayDate pure date targetPath <- resolveLogTarget bundlePath conceptId- let absolutePath = bundlePath </> targetPath- entry = Log.LogEntry {Log.logKind = Just kind, Log.logText = message}+ absolutePath <- tryBundleIo targetPath (requireBundlePath bundlePath targetPath) >>= either (dieText . renderBundleError) pure+ let entry = Log.LogEntry {Log.logKind = Just kind, Log.logText = message}+ refuse :: Text -> IO a refuse reason = dieText ("log: refusing to update " <> Text.pack absolutePath <> ": " <> reason <> ". No log content was written.") exists <- doesFileExist absolutePath original <-@@ -2340,6 +2358,7 @@ bytes <- Bytes.readFile absolutePath Just <$> either (\_ -> refuse "log is not valid UTF-8") pure (Text.Encoding.decodeUtf8' bytes) else pure Nothing+ when (maybe False hasFrontmatterFence original) (refuse "log.md must not have YAML frontmatter") updated <- either refuse pure (Log.insertLogEntry entryDate entry (fromMaybe (Log.serializeLog (emptyLogFor targetPath)) original)) if previewOnly then Bytes.putStr (Text.Encoding.encodeUtf8 (Log.renderLogDiff absolutePath original updated))@@ -2444,7 +2463,9 @@ runGraph GraphOptions {bundlePath} = do resolvedBundle <- resolveBundlePath bundlePath concepts <- loadBundleOrExit resolvedBundle- LazyByteString.putStrLn (Aeson.encode (buildGraph concepts))+ inventory <- loadBundleInventoryOrExit resolvedBundle+ declaration <- loadBundleVersionOrExit resolvedBundle+ LazyByteString.putStrLn (Aeson.encode (buildGraphWith declaration inventory concepts)) runShow :: ShowOptions -> IO () runShow ShowOptions {bundlePath, conceptIdText, profilePath, computationOnly, conceptOrder} = do@@ -2452,13 +2473,13 @@ Just rawIdentifier -> do resolvedBundle <- resolveBundlePath bundlePath concepts <- loadBundleOrExit resolvedBundle- let render = if computationOnly then renderComputation resolvedBundle else renderConcept+ let render = if computationOnly then renderComputation resolvedBundle else renderConcept resolvedBundle showConceptByIdentifier render profilePath concepts rawIdentifier Nothing -> do fzfConfig <- detectFzfConfig resolvedBundle <- resolveBundlePathWith fzfConfig bundlePath concepts <- loadBundleOrExit resolvedBundle- let render = if computationOnly then renderComputation resolvedBundle else renderConcept+ let render = if computationOnly then renderComputation resolvedBundle else renderConcept resolvedBundle selection <- selectConcept fzfConfig conceptOrder resolvedBundle concepts case selection of ConceptChosen concept -> render concept@@ -2468,47 +2489,39 @@ ConceptSelectionUnavailable -> dieNoConceptPicker ConceptSelectionError message -> dieConceptFzf message --- | Report the OKF v0.2 trust tier (§5.3), lifecycle status (§5.4), and--- staleness (§5.5) for every concept in a bundle, one aligned line each.------ Reads the clock exactly once and passes the day to 'staleness' for every--- concept, so a run that straddles midnight cannot report two concepts against--- different notions of "today". @okf-core@ never reads the clock itself; see--- @docs\/adr\/8-derived-not-stored-trust-and-credibility.md@.------ Output is sorted by concept ID, which 'walkBundle' already guarantees, so the--- report is stable and diffable in pipelines and CI.+-- | Report current verification, lifecycle status and freshness using one+-- clock reading for every concept in the report. runTrust :: TrustOptions -> IO () runTrust TrustOptions {bundlePath} = do resolvedBundle <- resolveBundlePath bundlePath concepts <- loadBundleOrExit resolvedBundle- today <- utctDay <$> getCurrentTime- let rows = trustRow today <$> concepts+ now <- getCurrentTime+ let summaries = [(concept, conceptVerification concept) | concept <- concepts]+ rows = map (trustRow now) summaries widthOf column = maximum (0 : map (Text.length . column) rows) (idWidth, tierWidth, statusWidth) = (widthOf (\(a, _, _, _) -> a), widthOf (\(_, b, _, _) -> b), widthOf (\(_, _, c, _) -> c))- mapM_- ( \(conceptId, tier, status, stale) ->- Text.IO.putStrLn- ( Text.intercalate- " "- [ pad idWidth conceptId,- pad tierWidth tier,- pad statusWidth status,- stale- ]- )- )- rows+ for_ summaries (uncurry warnUnknownComparison)+ for_ rows $ \(conceptId, tier, status, stale) ->+ Text.IO.putStrLn $+ Text.intercalate " " [pad idWidth conceptId, pad tierWidth tier, pad statusWidth status, stale] where pad width cell = cell <> Text.replicate (width - Text.length cell) " "- trustRow today concept =+ trustRow now (concept, summary) = ( renderConceptId (conceptIdOf concept),- renderTrustTier (trustTier (conceptVerified concept)),+ renderTrustTier (trustTier (currentVerifications summary)), renderStatus (conceptStatus concept),- renderStaleness (staleness today (conceptStaleAfter concept))+ renderStaleness (stalenessAt now (conceptStaleAfter concept)) ) +conceptVerification :: Concept -> VerificationSummary+conceptVerification concept = summarizeVerification (conceptGenerated concept) (conceptVerified concept)++warnUnknownComparison :: Concept -> VerificationSummary -> IO ()+warnUnknownComparison concept summary =+ when (comparisonTimeUnknown summary) $+ Text.IO.hPutStrLn stderr (renderConceptId (conceptIdOf concept) <> ": cannot compare verification with missing or malformed generated.at")+ -- | List the OKF v0.2 @sources@ provenance recorded by each concept -- (specification §5.1), with the credibility signals that frame it. --@@ -2597,68 +2610,77 @@ -- with no provenance: an empty report is not an error. runComputations :: ComputationsOptions -> IO () runComputations ComputationsOptions {bundlePath} = do- resolvedBundle <- resolveBundlePath bundlePath- concepts <- loadBundleOrExit resolvedBundle- mapM_ Text.IO.putStrLn (computationReport concepts)+ root <- resolveBundlePath bundlePath+ concepts <- loadBundleOrExit root+ (declaration, inventory) <- loadComputationContext root+ mapM_ Text.IO.putStrLn (computationReportWith declaration inventory concepts) --- | The lines @okf computations@ prints, as data. Pure and separate from--- 'runComputations' so a test can assert the whole report rather than only the--- accessors behind it; 'renderProfileDetail' is exported for the same reason.------ Concepts arrive in 'walkBundle' order and keep it. Column widths are computed--- over the selected rows only, so one unrelated long concept ID elsewhere in the--- bundle cannot pad this report.+-- | Report in-memory concepts using the paths available from those concepts. computationReport :: [Concept] -> [Text] computationReport concepts =+ computationReportWith VersionUndeclared (bundleInventoryOfConcepts concepts) concepts++-- | Report the selected location and the readiness of each definition in the+-- actual bundle. The report never asserts a verdict about a run.+computationReportWith :: VersionDeclaration -> BundleInventory -> [Concept] -> [Text]+computationReportWith declaration inventory concepts = [ Text.intercalate " " [ pad idWidth conceptId, pad runtimeWidth runtime, pad parameterWidth parameters,- pad computationWidth computation,- contract+ pad locationWidth location,+ readiness ]- | (conceptId, runtime, parameters, computation, contract) <- rows+ | (conceptId, runtime, parameters, location, readiness) <- rows ] where- rows = computationRow <$> filter isAttestedComputation concepts+ rows = map computationRow (filter isAttestedComputation concepts) widthOf column = maximum (0 : map (Text.length . column) rows)- (idWidth, runtimeWidth, parameterWidth, computationWidth) =+ (idWidth, runtimeWidth, parameterWidth, locationWidth) = ( widthOf (\(a, _, _, _, _) -> a), widthOf (\(_, b, _, _, _) -> b), widthOf (\(_, _, c, _, _) -> c), widthOf (\(_, _, _, d, _) -> d) ) pad width cell = cell <> Text.replicate (width - Text.length cell) " "- isAttestedComputation concept = conceptType concept == attestedComputationType computationRow concept =- ( renderConceptId (conceptIdOf concept),- fromMaybe "(no runtime)" (conceptRuntime concept),- case conceptParameters concept of- [] -> "(no parameters)"- parameters -> Text.intercalate ", " (renderParameter <$> parameters),- computationLocation (conceptComputationSources concept),- contractHalves concept- )- -- Where §10.3 says the computation lives. Naming the count rather than- -- picking one of two is the honest answer: a concept offering both is what- -- `okf validate --strict` reports, and `okf show --computation` refuses it- -- for the same reason.- computationLocation = \case- [] -> "(no computation)"- [ComputationFile rawPath] -> rawPath- [ComputationInline _] -> "inline"- sources -> "(" <> countPhrase (length sources) "computation" <> ")"- -- Which of §10.2's two run-and-check halves the concept declares. Neither is- -- REQUIRED, so all four combinations are legitimate and the phrase says which- -- one this is rather than passing judgement on it.- contractHalves concept =- case (isJust (conceptExecutor concept), isJust (conceptAttester concept)) of- (True, True) -> "executor + attester"- (True, False) -> "executor"- (False, True) -> "attester"- (False, False) -> "(neither)"+ let location = locateComputation declaration inventory concept+ parameters = case conceptParameters concept of+ [] -> "(no parameters)"+ items -> Text.intercalate ", " (map renderParameter items)+ in ( renderConceptId (conceptIdOf concept),+ fromMaybe "(no runtime)" (conceptRuntime concept),+ parameters,+ renderComputationLocation location,+ declaredContractParts concept <> " | " <> renderComputationReadiness concept location+ ) +loadComputationContext :: FilePath -> IO (VersionDeclaration, BundleInventory)+loadComputationContext root = (,) <$> loadBundleVersionOrExit root <*> loadBundleInventoryOrExit root++isAttestedComputation :: Concept -> Bool+isAttestedComputation concept = conceptType concept == attestedComputationType++renderComputationLocation :: Either ComputationIssue LocatedComputation -> Text+renderComputationLocation = \case+ Right (InlineComputation _) -> "inline"+ Right (FileComputation path) -> "file " <> Text.pack path+ Left (UnusableComputationFile raw _) -> "missing file " <> raw+ Left _ -> "(missing computation)"++declaredContractParts :: Concept -> Text+declaredContractParts concept =+ case ["executor" | isJust (conceptExecutor concept)] <> ["attester" | isJust (conceptAttester concept)] of+ [] -> "(neither)"+ declaredParts -> Text.intercalate " + " declaredParts++renderComputationReadiness :: Concept -> Either ComputationIssue LocatedComputation -> Text+renderComputationReadiness concept location =+ case missingContractParts concept location of+ [] -> "eligible definition (run not checked)"+ missing -> "incomplete: missing " <> Text.intercalate ", " missing+ -- | List the concepts a bundle holds, one aligned line each. -- -- The whole-bundle reports that came before this one each answered a narrower@@ -2698,15 +2720,26 @@ showFields, sortKeys, profilePath,- json+ json,+ current } = do resolvedBundle <- resolveBundlePath bundlePath traverse_ checkFiltersWithProfile profilePath concepts <- loadBundleOrExit resolvedBundle- let selected = sortConcepts sortKeys (filterConceptsWhere optionFilters fieldFilters concepts)+ let matches = filterConceptsWhere optionFilters fieldFilters concepts+ selected <-+ if current+ then do+ inventory <- loadBundleInventoryOrExit resolvedBundle+ declaration <- loadBundleVersionOrExit resolvedBundle+ let (stable, issues) = currentKnowledge declaration inventory concepts matches+ mapM_ (Text.IO.hPutStrLn stderr . renderReplacementIssue) issues+ pure stable+ else pure matches+ let ordered = sortConcepts sortKeys selected if json- then LazyByteString.putStrLn (Aeson.encode (conceptReportJson selected))- else mapM_ Text.IO.putStrLn (conceptReport showFields selected)+ then LazyByteString.putStrLn (Aeson.encode (conceptReportJson ordered))+ else mapM_ Text.IO.putStrLn (conceptReport showFields ordered) where -- @--type@ is sugar for a filter on the @type@ key rather than a separate -- mechanism, so there is one matching path to reason about and to test,@@ -2736,6 +2769,13 @@ mapM_ (Text.IO.hPutStrLn stderr) diagnostics exitWith (ExitFailure 1) +renderReplacementIssue :: ReplacementIssue -> Text+renderReplacementIssue = \case+ ReplacementCycle source repeatedConcept ->+ renderConceptId source <> ": replacement cycle at " <> renderConceptId repeatedConcept+ MissingReplacement source raw ->+ renderConceptId source <> ": no in-bundle replacement at " <> raw+ -- | Every profile diagnostic for an @okf concepts@ command line, in a stable -- order: the legacy filters first — @--type@, legacy @--where@ equalities, -- @--has@, @--missing@, as they always have been — then each explicit@@ -3128,6 +3168,8 @@ renderConceptId conceptId <> ": " <> renderValidationErrorText error_ DanglingReference source target -> renderConceptId source <> ": link to missing concept: " <> renderConceptId target+ DanglingBodyPath source target ->+ renderConceptId source <> ": link to missing path: " <> Text.pack target DanglingFrontmatterPath source fieldName target alternative -> renderConceptId source <> ": "@@ -3591,6 +3633,8 @@ <> supersededIn <> "); move it to the optional list" <> maybe "" (\replacement -> " or replace it with " <> replacement) (supersededBy (renderFieldPath target))+ ReplacementFieldMustBePath scope ->+ renderScope scope <> " requires superseded_by to name one file path in OKF 0.3" FormatRequiresOkfVersion scope target fieldFormat declared introducedIn -> renderScope scope <> ": declared okfVersion "@@ -3631,6 +3675,8 @@ Integer -> "integer" NonNegativeInteger -> "non-negative-integer" FiniteDecimal -> "finite-decimal"+ OkfTimestamp -> "okf-timestamp"+ OkfActor -> "okf-actor" Boolean -> "boolean" renderHandleReferenceRule :: HandleReferenceRule -> Text@@ -3685,7 +3731,10 @@ MissingRequiredField fieldName -> "missing required field: " <> fieldName FieldMustBeNonEmptyText fieldName -> "field must be non-empty text: " <> fieldName MissingRecommendedField fieldName -> "missing recommended field: " <> fieldName- FieldMustBeListOfText fieldName -> "field must be a list of text values: " <> fieldName+ FieldMustBeListOfText fieldName -> "field must be text or a list of text values: " <> fieldName+ FamilyEntryMissing family entryIndex keys ->+ family <> " entry " <> Text.pack (show entryIndex) <> " is missing " <> Text.intercalate ", " keys+ MalformedTimestamp fieldName raw -> fieldName <> " is not an RFC 3339 date or instant: " <> renderJsonValue raw MissingGeneratedField -> "missing generated field (or legacy timestamp)" GeneratedMustHaveActor -> "generated must carry a by actor" SourceMissingResource entryIndex -> "sources entry is missing resource: index " <> Text.pack (show entryIndex)@@ -3698,6 +3747,7 @@ <> maybe "" (\replacement -> " (use " <> replacement <> ")") (supersededBy fieldName) AttestedComputationMissingRuntime -> attestedComputationType <> " concepts must declare runtime"+ AttestedComputationInvalidPath raw -> "computation must be a URI path: " <> renderJsonValue raw AttestedComputationHasNoComputation -> attestedComputationType <> " declares no computation: add a code block under a # Computation heading, or a computation path"@@ -3742,8 +3792,8 @@ renderLogPreview logFile = renderIndexPreview (logSourcePath logFile, Log.serializeLog (logContent logFile)) -renderConcept :: Concept -> IO ()-renderConcept concept = do+renderConcept :: FilePath -> Concept -> IO ()+renderConcept root concept = do Text.IO.putStrLn ("id: " <> renderConceptId (conceptIdOf concept)) mapM_ (\(fieldName, handle) -> Text.IO.putStrLn (fieldName <> ": " <> handle))@@ -3760,26 +3810,25 @@ unless (null (conceptParameters concept)) (Text.IO.putStrLn ("parameters: " <> Text.intercalate ", " (renderParameter <$> conceptParameters concept)))- -- Where the computation lives, in both of §10.3's forms. Without the inline- -- line a reader cannot tell "carries a computation in its body" from "carries- -- none at all". Exactly one line is printed: a concept somehow offering both- -- is `okf validate --strict`'s diagnostic, and `okf show` is not a validator.- case conceptComputationSources concept of- ComputationFile rawPath : _ -> Text.IO.putStrLn ("computation: " <> rawPath)- ComputationInline literal : _ ->- Text.IO.putStrLn ("computation: inline (" <> countPhrase (length (Text.lines literal)) "line" <> ")")- [] -> pure ()+ when (isAttestedComputation concept) $ do+ (declaration, inventory) <- loadComputationContext root+ let location = locateComputation declaration inventory concept+ Text.IO.putStrLn ("computation: " <> renderComputationLocation location)+ Text.IO.putStrLn ("contract: " <> renderComputationReadiness concept location) traverse_ (Text.IO.putStrLn . ("executor: " <>) . renderExecutor) (conceptExecutor concept) traverse_ (Text.IO.putStrLn . ("attester: " <>)) (attesterResource =<< conceptAttester concept) traverse_ (Text.IO.putStrLn . ("generated: " <>) . renderGenerated) (conceptGenerated concept)- Text.IO.putStrLn ("trust: " <> renderTrustTier (trustTier (conceptVerified concept)))- traverse_ (Text.IO.putStrLn . ("verified: " <>)) (latestVerification (conceptVerified concept))+ let summary = conceptVerification concept+ warnUnknownComparison concept summary+ Text.IO.putStrLn ("trust: " <> renderTrustTier (trustTier (currentVerifications summary)))+ traverse_ (Text.IO.putStrLn . ("verified: " <>)) (latestVerification (currentVerifications summary))+ traverse_ (Text.IO.putStrLn . ("verified before the last change: " <>)) (latestVerification (earlierVerifications summary))+ when (comparisonTimeUnknown summary) $+ traverse_ (Text.IO.putStrLn . ("verification on record: " <>)) (latestVerification (conceptVerified concept)) Text.IO.putStrLn ("status: " <> renderStatus (conceptStatus concept))- -- Staleness is a comparison against today, so this is the one line that needs- -- the clock. okf-core never reads it; the CLI does, here and in `okf trust`.- today <- utctDay <$> getCurrentTime+ now <- getCurrentTime let staleAfterRaw = conceptStaleAfter concept- case staleness today staleAfterRaw of+ case stalenessAt now staleAfterRaw of NoStaleAfter -> pure () stale -> Text.IO.putStrLn ("stale_after: " <> renderStaleAfterDetail staleAfterRaw stale) case length (conceptSources concept) of@@ -3790,71 +3839,27 @@ Text.IO.putStrLn "" Text.IO.putStr (bodyText concept) --- | Print a concept's computation and nothing else, in whichever of--- specification §10.3's two forms the producer chose.------ This is the half of §10.5's consumer workflow a caller would otherwise--- reimplement: "Load the contract from frontmatter and the computation from the--- body (or the file named by @computation@)". The parenthesis is the expensive--- part, because it drags in §6.2's path grammar — where a bare--- @references\/x.sql@ resolves against the concept's own directory rather than--- the bundle root — and okf already owns that grammar in "Okf.Path".------ Reading a file the bundle holds is not executing anything. §10's boundary is--- that OKF "records the computation and the means to check it; it does not--- execute anything itself", which is about running computations rather than--- about opening files. The IO is CLI-side because @okf-core@ validation is--- offline by design; see--- @docs\/adr\/5-compile-profile-rules-before-validation.md@.------ Offering no computation, or more than one, exits non-zero rather than--- guessing. Printing an arbitrary one of two would answer a question the bundle--- has not settled.+-- | Read the sanctioned definition after selecting it against the inventory. renderComputation :: FilePath -> Concept -> IO ()-renderComputation bundleRoot concept =- case conceptComputationSources concept of- [ComputationInline literal] -> Text.IO.putStr literal- [ComputationFile rawPath] ->- case classifyPathReference (conceptIdOf concept) rawPath of- BundlePath target -> do- let absolutePath = bundleRoot </> target- exists <- doesFileExist absolutePath- unless exists $- dieText (conceptPrefix <> "computation names " <> Text.pack target <> ", which the bundle does not hold")- Text.IO.putStr =<< Text.IO.readFile absolutePath- ExternalUrl scheme ->- dieText- ( conceptPrefix- <> "computation is a "- <> scheme- <> " URL; okf has no network access and never fetches a computation"- )- EscapesBundle ->- dieText (conceptPrefix <> "computation names a path that climbs above the bundle root")- MalformedPath ->- dieText (conceptPrefix <> "computation is not a usable path")- [] ->- dieText- ( conceptPrefix- <> "offers no computation: it names no computation path and carries no code block under a # Computation heading"- )- sources ->- dieText- ( conceptPrefix- <> "offers more than one computation, so okf cannot say which one to run: "- <> Text.intercalate " and " (describeSource <$> sources)- <> "\nRun okf validate --strict to see this as a diagnostic."- )+renderComputation root concept = do+ (declaration, inventory) <- loadComputationContext root+ case locateComputation declaration inventory concept of+ Right (InlineComputation literal) -> Text.IO.putStr literal+ Right (FileComputation target) -> do+ loaded <- tryBundleIo target (requireBundlePath root target >>= Text.IO.readFile)+ either (dieText . renderBundleError) Text.IO.putStr loaded+ Left problem -> dieText (renderConceptId (conceptIdOf concept) <> ": " <> describeIssue problem) where- conceptPrefix = renderConceptId (conceptIdOf concept) <> ": "- describeSource = \case- ComputationFile rawPath -> "the file " <> rawPath- ComputationInline literal ->- "an inline block of " <> countPhrase (length (Text.lines literal)) "line"+ describeIssue = \case+ NoComputationFence -> "no fenced block in an ATX Computation section"+ InvalidComputationReference raw -> "computation must be a URI path: " <> renderJsonValue raw+ UnusableComputationFile raw resolution ->+ case resolution of+ DanglingInBundle path -> "computation names " <> Text.pack path <> ", which the bundle does not hold as a file"+ UnresolvableEscape -> "computation path leaves the bundle: " <> raw+ ResolvedExternal scheme -> "computation is an external " <> scheme <> " URI: " <> raw+ _ -> "computation is not a usable file path: " <> raw --- | Render one attested-computation parameter as @\<name\> (\<type\>,--- required)@, dropping whichever of the two optional members the concept omits--- (specification §10.2). renderParameter :: Parameter -> Text renderParameter Parameter {parameterName, parameterType, parameterRequired} = parameterName <> if null qualifiers then "" else " (" <> Text.intercalate ", " qualifiers <> ")"@@ -3890,6 +3895,7 @@ NoStaleAfter -> "" Fresh -> raw <> " (ok)" Stale _ -> raw <> " (stale)"+ StaleAt _ -> raw <> " (stale)" StaleAfterUnparseable _ -> raw <> " (unparseable)" where raw = fromMaybe "" rawValue@@ -3914,6 +3920,7 @@ renderBundleError = \case InvalidConceptPath path error_ -> Text.pack path <> ": " <> renderConceptIdParseError error_ InvalidConceptDocument path error_ -> Text.pack path <> ": " <> renderDocumentParseError error_+ InvalidReservedFile path message -> Text.pack path <> ": " <> message BundleIoError path message -> Text.pack path <> ": " <> message renderConceptIdError :: Text -> ConceptIdError -> Text
test/Main.hs view
@@ -58,7 +58,7 @@ import System.Exit (ExitCode (..), exitFailure) import System.FilePath (normalise, takeDirectory, takeFileName, (</>)) import System.IO (Handle, IOMode (..), hClose, hFlush, stderr, stdout, withFile)-import System.IO.Temp (createTempDirectory)+import System.IO.Temp (createTempDirectory, withSystemTempDirectory) import System.Process (readProcessWithExitCode) import System.Timeout (timeout) @@ -89,6 +89,9 @@ profileDiscoveryListing <- testProfileDiscoveryListing profilePickerExitCodes <- testProfilePickerExitCodes effectiveProfileSources <- testEffectiveProfileSources+ mixedBundle <- testMixedBundleValidation+ trustAndLifecycle <- testTrustAndLifecycle+ computationLocator <- testComputationLocator logAddWrites <- testLogAddWritesFile logAddPreserves <- testLogAddPreservesHistory logAddPreview <- testLogAddPreview@@ -138,7 +141,10 @@ conceptMenuOrdering <- testConceptMenuOrdering nonAsciiDiagnostics <- testNonAsciiValuesSurviveDiagnostics let results =- [ nestedClosureCli,+ [ mixedBundle,+ trustAndLifecycle,+ computationLocator,+ nestedClosureCli, profileSweepCli, productDiscoveryCli, fzfCancellation,@@ -199,7 +205,7 @@ (Computations (ComputationsOptions Nothing)), parseCommandMatches ["concepts"]- (Concepts (ConceptsOptions Nothing [] [] [] [] [] [] Nothing False)),+ (Concepts (ConceptsOptions Nothing [] [] [] [] [] [] Nothing False False)), parseIdMatches ["id", "next", "ADR", "--profile", "p.dhall"] (IdOptions Nothing "p.dhall" (IdNext "ADR")),@@ -579,7 +585,8 @@ showFields = [], sortKeys = [], profilePath = Nothing,- json = False+ json = False,+ current = False }, parseConceptsMatches ["concepts", "b", "--json"]@@ -592,7 +599,8 @@ showFields = [], sortKeys = [], profilePath = Nothing,- json = True+ json = True,+ current = False }, parseConceptsMatches ["concepts", "b", "--type", "Policy", "--where", "status=accepted", "--show", "requestId"]@@ -605,7 +613,8 @@ showFields = ["requestId"], sortKeys = [], profilePath = Nothing,- json = False+ json = False,+ current = False }, parseConceptsMatches ["concepts", "b", "--has", "completedAt", "--missing", "reviews.outcome"]@@ -618,7 +627,8 @@ showFields = [], sortKeys = [], profilePath = Nothing,- json = False+ json = False,+ current = False }, -- A filter is rejected before the bundle is walked: no '=' at all, and -- a key nesting deeper than one level.@@ -659,7 +669,8 @@ showFields = [], sortKeys = [], profilePath = Nothing,- json = False+ json = False,+ current = False }, -- Malformed extended input is rejected rather than read as equality. parseFails ["concepts", "b", "--where", "status in []"],@@ -686,7 +697,8 @@ SortKey (TopLevelField "title") Ascending ], profilePath = Nothing,- json = False+ json = False,+ current = False }, parseSucceeds ["concepts", "b", "--sort", "reviews.outcome:desc"], parseFails ["concepts", "b", "--sort", "status:up"],@@ -2058,12 +2070,12 @@ testComputationsReportsFixtureBundle = assertComputationReport ("okf-core" </> "test" </> "fixtures" </> "attested-computation")- [ "computations/both-computations bigquery (no parameters) (2 computations) (neither)",- "computations/churn bigquery year inline executor",- "computations/margin (no runtime) year (integer, required) inline (neither)",- "computations/no-computation bigquery (no parameters) (no computation) (neither)",- "computations/revenue bigquery year (integer, required) inline executor + attester",- "computations/two-blocks bigquery (no parameters) (2 computations) (neither)"+ [ "computations/both-computations bigquery (no parameters) file references/queries/revenue.sql (neither) | incomplete: missing attester",+ "computations/churn bigquery (no parameters) inline executor | incomplete: missing attester",+ "computations/margin (no runtime) year (integer, required) inline (neither) | incomplete: missing runtime, attester",+ "computations/no-computation bigquery (no parameters) (missing computation) (neither) | incomplete: missing attester, computation",+ "computations/revenue bigquery year (integer, required) inline executor + attester | eligible definition (run not checked)",+ "computations/two-blocks bigquery (no parameters) inline (neither) | incomplete: missing attester" ] -- | @okf computations@ over the shipped example, whose twenty-two concepts@@ -2073,7 +2085,7 @@ testComputationsReportsExampleBundle = assertComputationReport ("examples" </> "ddd-ordering")- ["computations/order-total postgres order_id (uuid, required) inline executor + attester"]+ ["computations/order-total postgres order_id (uuid, required) inline executor + attester | eligible definition (run not checked)"] -- | @okf concepts@ with no filters over the concept-filter fixture bundle: one -- row per concept, three columns, sorted by concept ID. The column widths are@@ -2449,12 +2461,14 @@ assertComputationReport relativeBundle expected = withRepositoryPath ("okf computations over " <> relativeBundle) relativeBundle $ \bundleRoot -> do walked <- walkBundle bundleRoot- case walked of+ inventory <- walkBundleInventory bundleRoot+ version <- readBundleVersion bundleRoot+ case computationReportWith <$> version <*> inventory <*> walked of Left bundleError -> do putStrLn ("failed to walk " <> relativeBundle <> ": " <> show bundleError) pure False- Right concepts -> do- let actual = computationReport concepts+ Right report -> do+ let actual = map Text.unwords (map Text.words report) unless (actual == expected) $ putStrLn ( "unexpected okf computations report for "@@ -2579,8 +2593,8 @@ Nothing -> error "0.2 must parse as an OKF version" unless (declared == expected) $ putStrLn ("generated root index declares " <> show declared <> ", expected " <> show expected)- -- Regenerating without the flag must preserve the declaration rather than- -- silently stripping it.+ let header = "---\nokf_version: \"0.2\"\ntitle: 'Existing documentation' # keep\nx-extensions: { original: 'yes' }\n---\n"+ Text.IO.writeFile (destination </> "index.md") header runCommand ( Profile (ProfileDocument (exampleDocumentOptions descriptorPath destination Nothing Nothing))@@ -2588,8 +2602,155 @@ preserved <- readBundleVersion destination unless (preserved == declared) $ putStrLn ("regenerating without --okf-version changed the declaration to " <> show preserved)- pure (declared == expected && preserved == declared)+ regenerated <- Text.IO.readFile (destination </> "index.md")+ pure (declared == expected && preserved == declared && header `Text.isPrefixOf` regenerated) +testComputationLocator :: IO Bool+testComputationLocator = withSystemTempDirectory "okf-computation-v03" $ \root -> do+ let fixture = root </> "metrics" </> "measure.md"+ asset = root </> "metrics" </> "sanctioned.sql"+ useBody extra markdown =+ Text.IO.writeFile fixture ("---\ntype: Attested Computation\n" <> extra <> "---\n" <> markdown)+ run args = captureStdout (captureHandle stderr (try @ExitCode (withArgs args runCli)))+ inspect = run ["show", root, "metrics/measure", "--computation"]+ oneFence = "### Computation\n\n SELECT 'indent';\n\n~~~sql\nSELECT 'first';\n~~~\n"+ twoFences = oneFence <> "\n```sql\nSELECT 'other';\n```\n"+ single = "runtime: postgres\nparameters: { name: id, type: uuid }\nattester: { resource: /checker.py }\n"+ createDirectoryIfMissing True (root </> "metrics")+ Text.IO.writeFile asset "SELECT 'file';\n"+ useBody ("computation: sanctioned.sql\n" <> single) twoFences+ ((file, _), fileOutput) <- inspect+ removeFile asset+ ((missing, fileError), _) <- inspect+ createDirectoryIfMissing True asset+ ((directory, _), directoryOutput) <- inspect+ sources <- forM ["", "computation: null\n", "computation: ''\n", "computation: []\n"] $ \emptyValue -> do+ useBody (emptyValue <> single) twoFences+ inspect+ let rejectedMarkdown =+ [ "### Computation\n\n SELECT 'indent';\n",+ "Computation\n-----------\n\n```sql\nSELECT 1;\n```\n",+ "### Computation\n\n### Next section\n\n```sql\nSELECT 2;\n```\n"+ ]+ rejected <- forM rejectedMarkdown $ \markdown -> do+ useBody single markdown+ inspect+ useBody "computation: ../../outside.sql\n" oneFence+ ((escaped, _), outsideOutput) <- inspect+ useBody "parameters: { name: missingType }\n" oneFence+ ((validation, advice), _) <- run ["validate", root]+ ((listing, _), computationOutput) <- run ["computations", root]+ useBody single twoFences+ ((complete, _), completeOutput) <- run ["computations", root]+ ((strictResult, strictErrors), _) <- run ["validate", root, "--strict"]+ let passed =+ file == Right ()+ && fileOutput == "SELECT 'file';\n"+ && missing == Left (ExitFailure 1)+ && "sanctioned.sql" `Text.isInfixOf` fileError+ && directory == Left (ExitFailure 1)+ && Text.null directoryOutput+ && all (\((status, _), output) -> status == Right () && output == "SELECT 'first';\n") sources+ && all (\((status, _), output) -> status == Left (ExitFailure 1) && Text.null output) rejected+ && escaped == Left (ExitFailure 1)+ && Text.null outsideOutput+ && validation == Right ()+ && "parameters entry 0 is missing type" `Text.isInfixOf` advice+ && listing == Right ()+ && "incomplete: missing runtime, attester" `Text.isInfixOf` computationOutput+ && complete == Right ()+ && all (`Text.isInfixOf` completeOutput) ["metrics/measure", "id (uuid, optional)", "eligible definition (run not checked)"]+ && strictResult == Left (ExitFailure 1)+ && "2 code blocks" `Text.isInfixOf` strictErrors+ unless passed $ print (fileOutput, fileError, sources, rejected, advice, computationOutput, completeOutput, strictErrors)+ pure passed++testTrustAndLifecycle :: IO Bool+testTrustAndLifecycle = withSystemTempDirectory "okf-trust-v03" $ \root -> do+ let run args = captureStdout (captureHandle stderr (try @ExitCode (withArgs args runCli)))+ doc name metadata =+ Text.IO.writeFile (root </> name <> ".md") ("---\ntype: Metric\n" <> metadata <> "---\n# Metric\n")+ doc "prior" "generated: { by: human:change, at: 2026-11-30T12:00:00Z }\nverified: { by: human:review, at: 2026-11-30T12:30:00+01:00 }\nstale_after: [soon]\n"+ doc "unknown" "generated: { by: human:change }\nverified: { by: human:review, at: 2026-11-30 }\n"+ doc "old" "status: deprecated\nsuperseded_by: /next.md\n"+ doc "next" "status: stable\nsuperseded_by: /wrong.md\n"+ doc "retired" "status: deprecated\n"+ doc "first-cycle" "status: deprecated\nsuperseded_by: second-cycle.md\n"+ doc "second-cycle" "status: deprecated\nsuperseded_by: first-cycle.md\n"+ doc "external" "status: deprecated\nsuperseded_by: 'file:///private/missing.md'\n"+ doc "house" "status: Accepted\n"+ ((trust, trustWarnings), trustOutput) <- run ["trust", root]+ ((shown, _), showOutput) <- run ["show", root, "prior"]+ ((unknown, unknownWarnings), unknownOutput) <- run ["show", root, "unknown"]+ ((latest, warnings), latestOutput) <- run ["concepts", root, "--current", "--where", "status=deprecated"]+ ((raw, _), rawOutput) <- run ["concepts", root, "--where", "status=Accepted"]+ ((currentHouse, _), houseOutput) <- run ["concepts", root, "--current", "--where", "status=Accepted"]+ ((retired, _), retiredOutput) <- run ["show", root, "retired"]+ let passed =+ all (== Right ()) [trust, shown, unknown, latest, raw, currentHouse, retired]+ && any (\line -> all (`Text.isInfixOf` line) ["prior", "unverified", "unparseable stale_after"]) (Text.lines trustOutput)+ && all (`Text.isInfixOf` showOutput) ["trust: unverified", "verified before the last change", "stale_after: [\"soon\"] (unparseable)"]+ && "trust: unverified" `Text.isInfixOf` unknownOutput+ && all ("missing or malformed generated.at" `Text.isInfixOf`) [trustWarnings, unknownWarnings]+ && map (take 1 . Text.words) (Text.lines latestOutput) == [["next"]]+ && all (`Text.isInfixOf` warnings) ["replacement cycle", "no in-bundle replacement"]+ && "house" `Text.isInfixOf` rawOutput+ && Text.null houseOutput+ && "status: deprecated" `Text.isInfixOf` retiredOutput+ unless passed $ print (trustOutput, trustWarnings, showOutput, unknownWarnings, latestOutput, warnings, rawOutput, houseOutput)+ pure passed++testMixedBundleValidation :: IO Bool+testMixedBundleValidation = withSystemTempDirectory "okf-cli-v03" $ \root -> do+ let run args = captureStdout (captureHandle stderr (try @ExitCode (withArgs args runCli)))+ validate = run ["validate", root]+ concept = "---\ntype: Unfamiliar\ntags: single,tag\n---\n# Concept\n"+ rootHeader = "---\nokf_version: '0.3'\n---\n"+ createDirectoryIfMissing True (root </> "nested")+ createDirectoryIfMissing True (root </> ".hidden")+ Text.IO.writeFile (root </> "knowledge.md") concept+ Text.IO.writeFile (root </> ".hidden" </> "hidden.md") concept+ Text.IO.writeFile (root </> "README.md") "# README\n"+ Text.IO.writeFile (root </> "SKILL.md") "---\nname: helper\n---\n# Instructions\n"+ Text.IO.writeFile (root </> "image.png") "asset"+ Text.IO.writeFile (root </> "log.md") "# Log\n\n## 2026-11-30\n- A plain prose entry.\n"+ Text.IO.writeFile (root </> "index.md") (rootHeader <> "# Knowledge\n")+ Text.IO.writeFile (root </> "nested" </> "index.md") "# Nested\n"+ ((valid, advice), summary) <- validate+ ((graph, _), graphOutput) <- run ["graph", root]+ Text.IO.writeFile (root </> "nested" </> "index.md") ""+ Text.IO.writeFile (root </> "index.md") rootHeader+ ((headingless, emptyErrors), _) <- validate+ Text.IO.writeFile (root </> "index.md") (rootHeader <> "# Knowledge\n")+ Text.IO.writeFile (root </> "nested" </> "index.md") ("---\ntype: Reserved\n---\n# Nested\n")+ ((nested, nestedErrors), _) <- validate+ Text.IO.writeFile (root </> "nested" </> "index.md") "# Nested\n"+ Text.IO.writeFile (root </> "log.md") "---\ntype: Reserved\n---\n# Log\n"+ ((withHeader, logErrors), _) <- validate+ Text.IO.writeFile (root </> "log.md") "# Log\n\n## 2026-02-30\n- Entry.\n"+ ((badDate, dateErrors), _) <- validate+ Text.IO.writeFile (root </> "broken.md") "---\nextra: [\n---\n"+ ((malformed, yamlErrors), _) <- validate+ let passed =+ valid == Right ()+ && "OK: 1 concepts (okf_version 0.3)" `Text.isInfixOf` summary+ && all (`Text.isInfixOf` advice) ["README.md", "SKILL.md", "skipped Markdown"]+ && graph == Right ()+ && "knowledge" `Text.isInfixOf` graphOutput+ && not (any (`Text.isInfixOf` graphOutput) ["README", "SKILL", "hidden"])+ && headingless == Left (ExitFailure 1)+ && all (`Text.isInfixOf` emptyErrors) ["index.md must contain a section heading", "nested/index.md"]+ && nested == Left (ExitFailure 1)+ && "nested/index.md: a nested index.md must not have YAML frontmatter" `Text.isInfixOf` nestedErrors+ && withHeader == Left (ExitFailure 1)+ && "log.md must not have YAML frontmatter" `Text.isInfixOf` logErrors+ && badDate == Left (ExitFailure 1)+ && "log.md: log date heading is not YYYY-MM-DD: 2026-02-30" `Text.isInfixOf` dateErrors+ && malformed == Left (ExitFailure 1)+ && "broken.md: invalid YAML frontmatter" `Text.isInfixOf` yamlErrors+ unless passed $ print (valid, advice, summary, graph, graphOutput, emptyErrors, nestedErrors, logErrors, dateErrors, yamlErrors)+ pure passed+ testLogAddWritesFile :: IO Bool testLogAddWritesFile = do temporaryDirectory <- getTemporaryDirectory@@ -2871,6 +3032,7 @@ ProfileDiscovery {searchRoots, descriptorPaths} <- discoverAvailableProfiles let expectedPaths = [ absoluteRoot </> "okf-v0-2.dhall",+ absoluteRoot </> "okf-v0-3.dhall", absoluteRoot </> "postgresql.dhall", absoluteRoot </> "profile-documentation.dhall" ]@@ -2951,6 +3113,7 @@ ) -> map (\ResolvedProfileSource {resolvedSource = source} -> source) discovered == [ DescriptorSource (absoluteRoot </> "okf-v0-2.dhall"),+ DescriptorSource (absoluteRoot </> "okf-v0-3.dhall"), DescriptorSource (absoluteRoot </> "postgresql.dhall"), DescriptorSource (absoluteRoot </> "profile-documentation.dhall") ]@@ -4035,15 +4198,17 @@ existingLog = "# Bundle Update Log\n\n" <> existingHistory createDirectoryIfMissing True (existing </> "nested") Text.IO.writeFile (existing </> "nested" </> "concept.md") conceptText- Text.IO.writeFile (existing </> "index.md") "---\nokf_version: \"0.3\"\n---\n"+ let existingHeader = "---\nokf_version: \"0.3\"\ntitle: 'Existing bundle' # retained\nlicense: CC-BY-4.0\n---\n"+ Text.IO.writeFile (existing </> "index.md") existingHeader Text.IO.writeFile (existing </> "log.md") existingLog existingResult <- run (options existing) preserved <- Text.IO.readFile (existing </> "nested" </> "concept.md") higher <- readBundleVersion existing+ existingIndex <- Text.IO.readFile (existing </> "index.md") appended <- Text.IO.readFile (existing </> "log.md") nestedIndex <- doesFileExist (existing </> "nested" </> "index.md") let (adoptionPrefix, historyAfter) = Text.breakOn existingHistory appended- existingOk <- success "existing bundle" (existingResult == Right () && preserved == conceptText && higher == Right (VersionDeclared (OkfVersion 0 3)) && historyAfter == existingHistory && "# Bundle Update Log\n\n## 2026-09-19\n* **Adoption**:" `Text.isPrefixOf` adoptionPrefix && Text.count "**Adoption**" appended == 1 && nestedIndex)+ existingOk <- success "existing bundle" (existingResult == Right () && preserved == conceptText && existingHeader `Text.isPrefixOf` existingIndex && higher == Right (VersionDeclared (OkfVersion 0 3)) && historyAfter == existingHistory && "# Bundle Update Log\n\n## 2026-09-19\n* **Adoption**:" `Text.isPrefixOf` adoptionPrefix && Text.count "**Adoption**" appended == 1 && nestedIndex) -- Invalid definitions load but must fail compilation before mutation. let invalidRegistry = root </> "invalid.dhall" Text.IO.writeFile invalidRegistry ("let registry = " <> Text.pack absoluteRegistry <> " in registry.postgresql with okfVersion = \"invalid\"")@@ -4067,14 +4232,16 @@ logDescriptor <- doesFileExist (logFailure </> "profile.dhall") logIndex <- doesFileExist (logFailure </> "index.md") logFailureOk <- success "log write recovery" (logResult == Left (ExitFailure 1) && logDescriptor && logIndex)- let invalidBundle = root </> "invalid-bundle"- createDirectoryIfMissing True invalidBundle- Text.IO.writeFile (invalidBundle </> "concept.md") "---\ntitle: Missing type\n---\nBody\n"- invalidResult <- run (options invalidBundle)- invalidLog <- doesFileExist (invalidBundle </> "log.md")- invalidDescriptor <- doesFileExist (invalidBundle </> "profile.dhall")- structuralOk <- success "post-write validation" (invalidResult == Left (ExitFailure 1) && invalidLog && invalidDescriptor)- pure (and [previewOk, greenOk, dateOk, dateSyntaxOk, directoryOk, danglingOk, danglingBundleOk, fileTargetOk, versionOk, existingOk, invalidOk, mismatchOk, indexFailureOk, logFailureOk, structuralOk])+ let untypedBundle = root </> "untyped-bundle"+ readme = "---\ntitle: Adoption notes\n---\nBody\n"+ createDirectoryIfMissing True untypedBundle+ Text.IO.writeFile (untypedBundle </> "README.md") readme+ untypedResult <- run (options untypedBundle)+ untypedLog <- doesFileExist (untypedBundle </> "log.md")+ untypedDescriptor <- doesFileExist (untypedBundle </> "profile.dhall")+ readmeAfter <- Text.IO.readFile (untypedBundle </> "README.md")+ untypedOk <- success "adoption with untyped Markdown" (untypedResult == Right () && untypedLog && untypedDescriptor && readme == readmeAfter)+ pure (and [previewOk, greenOk, dateOk, dateSyntaxOk, directoryOk, danglingOk, danglingBundleOk, fileTargetOk, versionOk, existingOk, invalidOk, mismatchOk, indexFailureOk, logFailureOk, untypedOk]) -- A refusal is an error-shaped value, so it cannot be mistaken for an argv -- that a consumer may spawn. Keep this compatibility boundary on upgrades.