///|
fn metadata_error_message(error : MetadataError) -> (String, Int32?) {
  match error {
    InvalidYaml(line~, message~, ..) =>
      ("invalid frontmatter: \{message}", Some(line))
    Unterminated => ("the frontmatter block has no closing `---` line", Some(1))
  }
}

///|
/// Each document whose frontmatter block is invalid.
fn check_frontmatter_invalid(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.documents() {
    let (bundle, doc) = pair
    match doc.metadata_error() {
      Some(error) => {
        let (message, line) = metadata_error_message(error)
        out.push(
          Issue::at(
            bundle,
            doc,
            message,
            line?,
            hint="Fix the YAML between the `---` lines.",
          ),
        )
      }
      None => ()
    }
  }
  out
}

///|
/// Each non-reserved Markdown document without a frontmatter block, unless a
/// profile derived its metadata.
fn check_concept_no_frontmatter(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.documents() {
    let (bundle, doc) = pair
    if doc.kind() is NonConcept &&
      !doc.has_frontmatter_block() &&
      !doc.is_derived() {
      out.push(
        Issue::at(
          bundle,
          doc,
          "the concept has no frontmatter",
          line=1,
          hint="Add a `---` block with at least `type`.",
        ),
      )
    }
  }
  out
}

///|
/// Each non-reserved Markdown document with valid metadata but no non-empty `type`.
fn check_concept_missing_type(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.documents() {
    let (bundle, doc) = pair
    let has_metadata = doc.written_metadata() is Some(_) || doc.is_derived()
    if doc.kind() is NonConcept && has_metadata && doc.concept_type() is None {
      out.push(
        Issue::at(
          bundle,
          doc,
          "the concept has no `type`",
          line=doc.metadata().line_of("type").unwrap_or(1),
        ),
      )
    }
  }
  out
}

///|
/// Each sub-index with a frontmatter block.
fn check_subindex_frontmatter(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.documents() {
    let (bundle, doc) = pair
    if doc.kind() is SubIndex && doc.has_frontmatter_block() {
      out.push(
        Issue::at(
          bundle,
          doc,
          "a sub-index has frontmatter",
          line=1,
          hint="Only the root index can carry `okf_version`.",
        ),
      )
    }
  }
  out
}

///|
/// Each root index frontmatter key other than `okf_version` and profile bundle keys.
fn check_root_index_keys(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for bundle in ctx.knowledge.bundles() {
    match bundle.root_index() {
      Some(doc) =>
        match doc.written_metadata() {
          Some(meta) =>
            for key in meta.keys() {
              if !ctx.vocabulary.knows_bundle_key(key) {
                out.push(
                  Issue::at(
                    bundle,
                    doc,
                    "the root index has the key `\{key}`",
                    line=meta.line_of(key).unwrap_or(1),
                  ),
                )
              }
            }
          None => ()
        }
      None => ()
    }
  }
  out
}

///|
/// Each `log.md` with a frontmatter block (OKF v0.3, section 9).
fn check_log_frontmatter(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.documents() {
    let (bundle, doc) = pair
    if doc.kind() is Log && doc.has_frontmatter_block() {
      out.push(
        Issue::at(
          bundle,
          doc,
          "`log.md` must not have frontmatter",
          line=1,
          hint="Remove the YAML frontmatter block from `log.md`.",
        ),
      )
    }
  }
  out
}

///|
/// Each log section whose heading is not a `YYYY-MM-DD` date.
fn check_log_undated(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.documents() {
    let (bundle, doc) = pair
    if doc.kind() is Log {
      for section in doc.log_model().undated_sections() {
        out.push(
          Issue::at(
            bundle,
            doc,
            "the log section `\{section.heading}` is not a `YYYY-MM-DD` date",
            line=section.line,
          ),
        )
      }
    }
  }
  out
}

///|
/// The OKF v0.2 conformance rules (section 11): parseable frontmatter and a
/// non-empty `type` on each concept, and `index.md` and `log.md` in their formats.
pub fn okf_v02_conformance() -> RuleSet {
  RuleSet("okf-v0.2", [
    Rule(builtin_rule("frontmatter-invalid"), Error, check_frontmatter_invalid),
    Rule(
      builtin_rule("concept-no-frontmatter"),
      Error,
      check_concept_no_frontmatter,
    ),
    Rule(
      builtin_rule("concept-missing-type"),
      Error,
      check_concept_missing_type,
    ),
    Rule(
      builtin_rule("subindex-has-frontmatter"),
      Error,
      check_subindex_frontmatter,
    ),
    Rule(builtin_rule("log-undated-section"), Error, check_log_undated),
  ])
}

///|
/// The OKF v0.3 conformance rules (section 11.1): every frontmatter block under
/// the bundle root parses as a YAML mapping without duplicate keys, sub-indexes
/// and `log.md` files have no frontmatter, and `log.md` date headings use
/// `YYYY-MM-DD`. Non-concept Markdown files do not fail conformance.
pub fn okf_v03_conformance() -> RuleSet {
  RuleSet("okf-v0.3", [
    Rule(builtin_rule("frontmatter-invalid"), Error, check_frontmatter_invalid),
    Rule(
      builtin_rule("subindex-has-frontmatter"),
      Error,
      check_subindex_frontmatter,
    ),
    Rule(builtin_rule("log-has-frontmatter"), Error, check_log_frontmatter),
    Rule(builtin_rule("log-undated-section"), Error, check_log_undated),
  ])
}

///|
fn concept_rule(
  check : (ValidationContext, Bundle, Document) -> Issue?,
) -> (ValidationContext) -> Array[Issue] {
  ctx => {
    let out = []
    for pair in ctx.knowledge.concepts() {
      match check(ctx, pair.0, pair.1) {
        Some(issue) => out.push(issue)
        None => ()
      }
    }
    out
  }
}

///|
fn has_metadata(doc : Document) -> Bool {
  doc.written_metadata() is Some(_) || doc.is_derived()
}

///|
fn check_missing_title(
  _ctx : ValidationContext,
  bundle : Bundle,
  doc : Document,
) -> Issue? {
  if has_metadata(doc) && doc.metadata().title() is None {
    Some(Issue::at(bundle, doc, "the concept has no `title`", line=1))
  } else {
    None
  }
}

///|
fn check_missing_description(
  _ctx : ValidationContext,
  bundle : Bundle,
  doc : Document,
) -> Issue? {
  if has_metadata(doc) && doc.metadata().description() is None {
    Some(Issue::at(bundle, doc, "the concept has no `description`", line=1))
  } else {
    None
  }
}

///|
fn check_status_unknown(
  _ctx : ValidationContext,
  bundle : Bundle,
  doc : Document,
) -> Issue? {
  match doc.metadata().status() {
    Some(Unknown(text)) =>
      Some(
        Issue::at(
          bundle,
          doc,
          "`status: \{text}` is not draft, stable or deprecated",
          line=doc.metadata().line_of("status").unwrap_or(1),
        ),
      )
    _ => None
  }
}

///|
fn check_stale(
  ctx : ValidationContext,
  bundle : Bundle,
  doc : Document,
) -> Issue? {
  let meta = doc.metadata()
  match meta.freshness(ctx.now, options=bundle.options()) {
    Stale(_) => {
      let limit = meta.stale_after().unwrap_or("")
      Some(
        Issue::at(
          bundle,
          doc,
          "`stale_after: \{limit}` has passed",
          line=meta.line_of("stale_after").unwrap_or(1),
        ),
      )
    }
    NoExpiry | Fresh(_) | Malformed(_) => None
  }
}

///|
fn check_stale_after_malformed(
  ctx : ValidationContext,
  bundle : Bundle,
  doc : Document,
) -> Issue? {
  let meta = doc.metadata()
  match meta.freshness(ctx.now, options=bundle.options()) {
    Malformed(limit) =>
      Some(
        Issue::at(
          bundle,
          doc,
          "`stale_after: \{limit}` is not a valid RFC 3339 timestamp",
          line=meta.line_of("stale_after").unwrap_or(1),
        ),
      )
    NoExpiry | Fresh(_) | Stale(_) => None
  }
}

///|
fn check_markdown_not_concept(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.documents() {
    let (bundle, doc) = pair
    if doc.kind() is NonConcept && doc.metadata_error() is None {
      let reason = if !doc.has_frontmatter_block() {
        "the Markdown file has no frontmatter and is not a concept"
      } else {
        "the Markdown file has no non-empty `type` and is not a concept"
      }
      out.push(Issue::at(bundle, doc, reason, line=1))
    }
  }
  out
}

///|
fn is_blank_value(value : Value) -> Bool {
  match value {
    Null => true
    Scalar(s) => s.length() == 0
    Seq(items) => items.is_empty()
    Mapping(_) => false
  }
}

///|
fn list_values(value : Value) -> Array[Value] {
  match value {
    Seq(items) => items.iter().collect()
    other => if is_blank_value(other) { [] } else { [other] }
  }
}

///|
fn check_timestamp_value(
  bundle : Bundle,
  doc : Document,
  key : String,
  label : String,
  value : String,
  date_only : Bool,
  out : Array[Issue],
) -> Unit {
  if Instant::parse(value, date_only~) is None {
    out.push(
      Issue::at(
        bundle,
        doc,
        "`\{label}: \{value}` is not a valid RFC 3339 timestamp",
        line=doc.metadata().line_of(key).unwrap_or(1),
      ),
    )
  }
}

///|
fn check_window_timestamps(
  bundle : Bundle,
  doc : Document,
  key : String,
  label : String,
  window : Fields,
  date_only : Bool,
  out : Array[Issue],
) -> Unit {
  match window.text("from") {
    Some(v) =>
      check_timestamp_value(
        bundle,
        doc,
        key,
        "\{label}.from",
        v,
        date_only,
        out,
      )
    None => ()
  }
  match window.text("to") {
    Some(v) =>
      check_timestamp_value(bundle, doc, key, "\{label}.to", v, date_only, out)
    None => ()
  }
}

///|
fn check_timestamps(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let meta = doc.metadata()
    let date_only = bundle.options().date_only_instants
    match meta.mappings("generated") {
      [g, ..] =>
        match g.text("at") {
          Some(at) =>
            check_timestamp_value(
              bundle, doc, "generated", "generated.at", at, date_only, out,
            )
          None => ()
        }
      [] => ()
    }
    for i, v in meta.mappings("verified") {
      match v.text("at") {
        Some(at) =>
          check_timestamp_value(
            bundle,
            doc,
            "verified",
            "verified[\{i}].at",
            at,
            date_only,
            out,
          )
        None => ()
      }
    }
    match meta.mappings("usage_window") {
      [w, ..] =>
        check_window_timestamps(
          bundle, doc, "usage_window", "usage_window", w, date_only, out,
        )
      [] => ()
    }
    for i, s in meta.mappings("sources") {
      match s.text("last_modified") {
        Some(ts) =>
          check_timestamp_value(
            bundle,
            doc,
            "sources",
            "sources[\{i}].last_modified",
            ts,
            date_only,
            out,
          )
        None => ()
      }
      match s.get("usage_window") {
        Some(Mapping(w)) =>
          check_window_timestamps(
            bundle,
            doc,
            "sources",
            "sources[\{i}].usage_window",
            w,
            date_only,
            out,
          )
        _ => ()
      }
    }
  }
  out
}

///|
fn check_date_only_comparison_timestamps(
  ctx : ValidationContext,
) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let meta = doc.metadata()
    match meta.mappings("generated") {
      [g, ..] =>
        match g.text("at") {
          Some(at) if Instant::is_date_only(at) =>
            out.push(
              Issue::at(
                bundle,
                doc,
                "`generated.at` should be a date-time rather than date-only `\{at}`",
                line=meta.line_of("generated").unwrap_or(1),
              ),
            )
          _ => ()
        }
      [] => ()
    }
    for i, v in meta.mappings("verified") {
      match v.text("at") {
        Some(at) if Instant::is_date_only(at) =>
          out.push(
            Issue::at(
              bundle,
              doc,
              "`verified[\{i}].at` should be a date-time rather than date-only `\{at}`",
              line=meta.line_of("verified").unwrap_or(1),
            ),
          )
        _ => ()
      }
    }
  }
  out
}

///|
fn check_actor_text(
  bundle : Bundle,
  doc : Document,
  key : String,
  label : String,
  raw : String,
  out : Array[Issue],
) -> Unit {
  match Actor::parse(raw) {
    Some(actor) if !actor.is_valid() =>
      out.push(
        Issue::at(
          bundle,
          doc,
          "`\{label}: \{raw}` is not a `/` or `:` actor",
          line=doc.metadata().line_of(key).unwrap_or(1),
        ),
      )
    _ => ()
  }
}

///|
fn check_actors(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let meta = doc.metadata()
    match meta.mappings("generated") {
      [g, ..] =>
        match g.text("by") {
          Some(by) =>
            check_actor_text(bundle, doc, "generated", "generated.by", by, out)
          None => ()
        }
      [] => ()
    }
    for i, v in meta.mappings("verified") {
      match v.text("by") {
        Some(by) =>
          check_actor_text(
            bundle,
            doc,
            "verified",
            "verified[\{i}].by",
            by,
            out,
          )
        None => ()
      }
    }
    for i, s in meta.mappings("sources") {
      match s.text("author") {
        Some(author) =>
          check_actor_text(
            bundle,
            doc,
            "sources",
            "sources[\{i}].author",
            author,
            out,
          )
        None => ()
      }
    }
  }
  out
}

///|
fn check_generated_incomplete(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let meta = doc.metadata()
    match meta.get("generated") {
      Some(value) if !is_blank_value(value) =>
        match value {
          Mapping(fields) if fields.text("by") is Some(_) => ()
          _ =>
            out.push(
              Issue::at(
                bundle,
                doc,
                "`generated` must be a mapping with a non-empty `by` field",
                line=meta.line_of("generated").unwrap_or(1),
              ),
            )
        }
      _ => ()
    }
  }
  out
}

///|
fn check_verified_incomplete(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let meta = doc.metadata()
    match meta.get("verified") {
      Some(value) if !is_blank_value(value) =>
        for i, item in list_values(value) {
          match item {
            Mapping(fields) if fields.text("by") is Some(_) &&
              fields.text("at") is Some(_) => ()
            _ =>
              out.push(
                Issue::at(
                  bundle,
                  doc,
                  "`verified[\{i}]` requires both `by` and `at`",
                  line=meta.line_of("verified").unwrap_or(1),
                ),
              )
          }
        }
      _ => ()
    }
  }
  out
}

///|
fn check_verified_before_change(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let meta = doc.metadata()
    let options = bundle.options()
    if meta.current_verifications(options~).is_empty() &&
      !meta.historical_verifications(options~).is_empty() {
      out.push(
        Issue::at(
          bundle,
          doc,
          "all `verified` events are older than `generated.at`",
          line=meta.line_of("verified").unwrap_or(1),
        ),
      )
    }
  }
  out
}

///|
fn check_source_incomplete(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let meta = doc.metadata()
    match meta.get("sources") {
      Some(value) if !is_blank_value(value) =>
        for i, item in list_values(value) {
          match item {
            Mapping(fields) if fields.text("resource") is Some(_) => ()
            _ =>
              out.push(
                Issue::at(
                  bundle,
                  doc,
                  "`sources[\{i}]` requires a `resource` field",
                  line=meta.line_of("sources").unwrap_or(1),
                ),
              )
          }
        }
      _ => ()
    }
  }
  out
}

///|
fn check_source_duplicate_id(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let meta = doc.metadata()
    let seen : Array[String] = []
    for source in meta.sources() {
      match source.id {
        Some(id) =>
          if seen.contains(id) {
            out.push(
              Issue::at(
                bundle,
                doc,
                "duplicate `sources[].id` value `\{id}`",
                line=meta.line_of("sources").unwrap_or(1),
              ),
            )
          } else {
            seen.push(id)
          }
        None => ()
      }
    }
  }
  out
}

///|
fn check_source_missing_usage_window(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let meta = doc.metadata()
    let has_shared = meta.usage_window() is Some(_)
    for i, source in meta.sources() {
      if source.usage_count is Some(_) &&
        !has_shared &&
        source.usage_window is None {
        out.push(
          Issue::at(
            bundle,
            doc,
            "`sources[\{i}].usage_count` has no `usage_window`",
            line=meta.line_of("sources").unwrap_or(1),
          ),
        )
      }
    }
  }
  out
}

///|
fn check_citation_unresolved(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let reported : Array[String] = []
    for item in doc.cited_sources() {
      let (citation, source) = item
      if source is None && !reported.contains(citation.label) {
        reported.push(citation.label)
        out.push(
          Issue::at(
            bundle,
            doc,
            "footnote `[^\{citation.label}]` has no `sources` entry with that `id`",
            line=citation.line,
          ),
        )
      }
    }
  }
  out
}

///|
fn check_superseded_by_not_deprecated(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  let registers = registers_of(ctx.profiles.iter().collect())
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    let meta = doc.metadata()
    guard meta.superseded_by() is Some(_) else { continue }
    let claimed_by_register = match doc.concept_type() {
      Some(ct) =>
        registers.any(r => {
          r.concept_type() == ct &&
          r.superseded_by_key() == Some(superseded_by_key)
        })
      None => false
    }
    if claimed_by_register {
      continue
    }
    if !(meta.effective_status(options=bundle.options()) is Some(Deprecated)) {
      out.push(
        Issue::at(
          bundle,
          doc,
          "`superseded_by` has a meaning only with `status: deprecated`",
          line=meta.line_of("superseded_by").unwrap_or(1),
        ),
      )
    }
  }
  out
}

///|
fn check_path_field_v02_fallback(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    for item in okf_path_fields(doc) {
      let (key, value, line, allows_free_text) = item
      if allows_free_text &&
        value.contains(" ") &&
        !value.has_prefix("/") &&
        !has_scheme(value) {
        continue
      }
      let res = resolve_field_path_in_bundle(bundle, doc, value)
      if res.used_v02_fallback {
        out.push(
          Issue::at(
            bundle,
            doc,
            "`\{key}: \{value}` resolves only from the bundle root via the v0.2 fallback",
            line?,
            hint="Write it as `/\{value}` or relative to this file.",
          ),
        )
      }
    }
  }
  out
}

///|
fn is_spdx_token(token : String) -> Bool {
  token.length() > 0 &&
  token
  .iter()
  .all(c => {
    (c >= 'a' && c <= 'z') ||
    (c >= 'A' && c <= 'Z') ||
    (c >= '0' && c <= '9') ||
    c == '.' ||
    c == '+' ||
    c == '-'
  })
}

///|
fn is_spdx_expression(text : String) -> Bool {
  let parts = text.split(" ").map(s => s.to_owned()).collect()
  if parts.is_empty() || parts.length() % 2 == 0 {
    return false
  }
  for i, part in parts {
    if i % 2 == 0 {
      if !is_spdx_token(part) {
        return false
      }
    } else if part != "AND" && part != "OR" && part != "WITH" {
      return false
    }
  }
  true
}

///|
fn check_license_invalid(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for bundle in ctx.knowledge.bundles() {
    guard bundle.root_index() is Some(root) else { continue }
    guard bundle.license() is Some(license_val) else { continue }
    if is_spdx_expression(license_val) {
      continue
    }
    let res = resolve_field_path_in_bundle(bundle, root, license_val)
    let ok = match res.resolution {
      StoreTarget(path~, escapes=false, ..) =>
        target_exists_in_bundle(bundle, path, None)
      _ => false
    }
    if !ok {
      out.push(
        Issue::at(
          bundle,
          root,
          "`license: \{license_val}` is not an SPDX expression or a file in the bundle",
          line=root.metadata().line_of("license").unwrap_or(1),
        ),
      )
    }
  }
  out
}

///|
fn check_computation_missing_runtime(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    if doc.is_attested_computation() && doc.metadata().runtime() is None {
      out.push(
        Issue::at(
          bundle,
          doc,
          "an `Attested Computation` requires a `runtime` field",
          line=1,
        ),
      )
    }
  }
  out
}

///|
fn check_computation_missing_body(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    if doc.is_attested_computation() &&
      doc.metadata().computation() is None &&
      doc.inline_computation_blocks().is_empty() {
      out.push(
        Issue::at(
          bundle,
          doc,
          "no `computation` field and no fenced code block in a `Computation` section",
          line=1,
        ),
      )
    }
  }
  out
}

///|
fn check_computation_both_file_and_inline(
  ctx : ValidationContext,
) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    if doc.is_attested_computation() &&
      doc.metadata().computation() is Some(_) &&
      !doc.inline_computation_blocks().is_empty() {
      out.push(
        Issue::at(
          bundle,
          doc,
          "do not combine a `computation` field with a fenced block in `Computation`",
          line=doc.metadata().line_of("computation").unwrap_or(1),
        ),
      )
    }
  }
  out
}

///|
fn check_computation_multiple_blocks(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    if doc.is_attested_computation() && doc.metadata().computation() is None {
      let blocks = doc.inline_computation_blocks()
      if blocks.length() > 1 {
        out.push(
          Issue::at(
            bundle,
            doc,
            "the `Computation` section has \{blocks.length()} fenced blocks; expected 1",
            line=blocks[1].line,
          ),
        )
      }
    }
  }
  out
}

///|
fn check_parameter_incomplete(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    guard doc.is_attested_computation() else { continue }
    let meta = doc.metadata()
    match meta.get("parameters") {
      Some(value) if !is_blank_value(value) =>
        for i, item in list_values(value) {
          match item {
            Mapping(fields) if fields.text("name") is Some(_) &&
              fields.text("type") is Some(_) => ()
            _ =>
              out.push(
                Issue::at(
                  bundle,
                  doc,
                  "`parameters[\{i}]` requires both `name` and `type`",
                  line=meta.line_of("parameters").unwrap_or(1),
                ),
              )
          }
        }
      _ => ()
    }
  }
  out
}

///|
fn check_executor_incomplete(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    guard doc.is_attested_computation() else { continue }
    let meta = doc.metadata()
    match meta.get("executor") {
      Some(value) if !is_blank_value(value) =>
        match value {
          Mapping(fields) => {
            if fields.text("resource") is None {
              out.push(
                Issue::at(
                  bundle,
                  doc,
                  "`executor` requires a `resource` field",
                  line=meta.line_of("executor").unwrap_or(1),
                ),
              )
            }
            match fields.get("receipt") {
              Some(Seq(_)) => ()
              _ =>
                out.push(
                  Issue::at(
                    bundle,
                    doc,
                    "`executor.receipt` must be a list of fields",
                    line=meta.line_of("executor").unwrap_or(1),
                  ),
                )
            }
          }
          _ =>
            out.push(
              Issue::at(
                bundle,
                doc,
                "`executor` must be a mapping with `resource` and `receipt`",
                line=meta.line_of("executor").unwrap_or(1),
              ),
            )
        }
      _ => ()
    }
  }
  out
}

///|
fn check_attester_incomplete(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    guard doc.is_attested_computation() else { continue }
    let meta = doc.metadata()
    match meta.get("attester") {
      Some(value) if !is_blank_value(value) =>
        match value {
          Mapping(fields) if fields.text("resource") is Some(_) => ()
          _ =>
            out.push(
              Issue::at(
                bundle,
                doc,
                "`attester` must be a mapping with a `resource` field",
                line=meta.line_of("attester").unwrap_or(1),
              ),
            )
        }
      _ => ()
    }
  }
  out
}

///|
fn check_computation_missing_attester(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    if doc.is_attested_computation() && doc.metadata().attester() is None {
      out.push(
        Issue::at(
          bundle,
          doc,
          "without an `attester`, values from this computation cannot be shown as attested",
          line=1,
        ),
      )
    }
  }
  out
}

///|
fn check_unknown_keys(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.concepts() {
    let (bundle, doc) = pair
    match doc.written_metadata() {
      Some(meta) =>
        for key in meta.keys() {
          if !ctx.vocabulary.knows(key) {
            out.push(
              Issue::at(
                bundle,
                doc,
                "the key `\{key}` is not in the OKF or profile vocabulary",
                line=meta.line_of(key).unwrap_or(1),
              ),
            )
          }
        }
      None => ()
    }
  }
  out
}

///|
fn check_not_indexed(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for bundle in ctx.knowledge.bundles() {
    if bundle.indexes().is_empty() {
      continue
    }
    for doc in bundle.unindexed_concepts() {
      out.push(
        Issue::at(
          bundle,
          doc,
          "no index of the bundle links to this concept",
          hint="Add an entry to the nearest `index.md`.",
        ),
      )
    }
  }
  out
}

///|
fn check_drift(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for bundle in ctx.knowledge.bundles() {
    for drift in bundle.description_drift() {
      out.push(
        Issue::at(
          bundle,
          drift.index,
          "the entry for \{drift.concept.path()} does not match its description",
          line=drift.entry.line,
          hint="Use: \{drift.expected}",
        ),
      )
    }
  }
  out
}

///|
fn check_duplicate_titles(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for bundle in ctx.knowledge.bundles() {
    let seen : Map[String, Document] = Map([])
    for doc in bundle.concepts() {
      guard doc.metadata().title() is Some(title) else { continue }
      let key = title.to_lower()
      match seen.get(key) {
        Some(first) =>
          out.push(
            Issue::at(
              bundle,
              doc,
              "the title `\{title}` is also used by \{first.path()}",
            ),
          )
        None => seen[key] = doc
      }
    }
  }
  out
}

///|
fn check_broken_links(ctx : ValidationContext) -> Array[Issue] {
  ctx.graph
  .broken()
  .map(edge => {
    Issue::in_bundle(
      edge.from,
      "the link to `\{edge.link.destination}` does not resolve",
      line?=edge.link.line_number(),
    )
  })
}

///|
fn check_escaping_links(ctx : ValidationContext) -> Array[Issue] {
  ctx.graph
  .edges()
  .iter()
  .filter(e => e.escapes && e.link.kind is BundleRooted)
  .map(edge => {
    Issue::in_bundle(
      edge.from,
      "the link to `\{edge.link.destination}` leaves the bundle",
      line?=edge.link.line_number(),
    )
  })
  .collect()
}

///|
fn check_strays(ctx : ValidationContext) -> Array[Issue] {
  ctx.knowledge
  .strays()
  .iter()
  .map(path => Issue::stray(path, "the Markdown file belongs to no bundle"))
  .collect()
}

///|
fn check_log_order(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.documents() {
    let (bundle, doc) = pair
    if doc.kind() is Log {
      match doc.log_model().order_problem() {
        Some((a, b)) =>
          out.push(
            Issue::at(
              bundle,
              doc,
              "`\{a.heading}` comes before the newer `\{b.heading}`",
              line=b.line,
            ),
          )
        None => ()
      }
    }
  }
  out
}

///|
fn check_unknown_version(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for bundle in ctx.knowledge.bundles() {
    if !bundle.knows_version() {
      match bundle.root_index() {
        Some(doc) => {
          let version = bundle
            .okf_version()
            .map(v => v.to_string())
            .unwrap_or("")
          out.push(
            Issue::at(
              bundle,
              doc,
              "OKF version \{version} is not known; read with best effort",
            ),
          )
        }
        None => ()
      }
    }
  }
  out
}

///|
fn check_ignored_logs(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for bundle in ctx.knowledge.bundles() {
    for path in bundle.ignored_logs() {
      out.push(
        Issue::in_bundle(
          { bundle: bundle.label(), path, },
          "the nested log is ignored",
        ),
      )
    }
  }
  out
}

///|
fn check_unresolved_references(ctx : ValidationContext) -> Array[Issue] {
  let out = []
  for pair in ctx.knowledge.documents() {
    let (bundle, doc) = pair
    for r in typed_references(ctx.knowledge, bundle, doc, profiles=ctx.profiles) {
      if !r.is_resolved() {
        out.push(
          Issue::at(
            bundle,
            doc,
            "`\{r.key}: \{r.value}` does not resolve",
            line?=r.line,
          ),
        )
      }
    }
  }
  out
}

///|
/// Advisory rules. They report quality and OKF v0.3 field-shape issues that
/// conformance tolerates; the caller sets their severity with `ValidationConfig`.
pub fn advisory() -> RuleSet {
  RuleSet("okf-advisory", [
    Rule(
      builtin_rule("markdown-not-concept"),
      Warning,
      check_markdown_not_concept,
    ),
    Rule(
      builtin_rule("concept-missing-title"),
      Warning,
      concept_rule(check_missing_title),
    ),
    Rule(
      builtin_rule("concept-missing-description"),
      Warning,
      concept_rule(check_missing_description),
    ),
    Rule(
      builtin_rule("status-unknown"),
      Warning,
      concept_rule(check_status_unknown),
    ),
    Rule(builtin_rule("stale-after-passed"), Warning, concept_rule(check_stale)),
    Rule(
      builtin_rule("stale-after-malformed"),
      Warning,
      concept_rule(check_stale_after_malformed),
    ),
    Rule(builtin_rule("timestamp-invalid"), Warning, check_timestamps),
    Rule(
      builtin_rule("timestamp-date-only"),
      Warning,
      check_date_only_comparison_timestamps,
    ),
    Rule(builtin_rule("actor-invalid"), Warning, check_actors),
    Rule(
      builtin_rule("generated-incomplete"),
      Warning,
      check_generated_incomplete,
    ),
    Rule(
      builtin_rule("verified-incomplete"),
      Warning,
      check_verified_incomplete,
    ),
    Rule(
      builtin_rule("verified-before-change"),
      Info,
      check_verified_before_change,
    ),
    Rule(builtin_rule("source-incomplete"), Warning, check_source_incomplete),
    Rule(
      builtin_rule("source-duplicate-id"),
      Warning,
      check_source_duplicate_id,
    ),
    Rule(
      builtin_rule("source-missing-usage-window"),
      Warning,
      check_source_missing_usage_window,
    ),
    Rule(
      builtin_rule("citation-unresolved"),
      Warning,
      check_citation_unresolved,
    ),
    Rule(
      builtin_rule("superseded-by-not-deprecated"),
      Warning,
      check_superseded_by_not_deprecated,
    ),
    Rule(
      builtin_rule("path-field-v02-fallback"),
      Warning,
      check_path_field_v02_fallback,
    ),
    Rule(builtin_rule("license-invalid"), Warning, check_license_invalid),
    Rule(
      builtin_rule("computation-missing-runtime"),
      Warning,
      check_computation_missing_runtime,
    ),
    Rule(
      builtin_rule("computation-missing-body"),
      Warning,
      check_computation_missing_body,
    ),
    Rule(
      builtin_rule("computation-both-file-and-inline"),
      Warning,
      check_computation_both_file_and_inline,
    ),
    Rule(
      builtin_rule("computation-multiple-blocks"),
      Warning,
      check_computation_multiple_blocks,
    ),
    Rule(
      builtin_rule("parameter-incomplete"),
      Warning,
      check_parameter_incomplete,
    ),
    Rule(
      builtin_rule("executor-incomplete"),
      Warning,
      check_executor_incomplete,
    ),
    Rule(
      builtin_rule("attester-incomplete"),
      Warning,
      check_attester_incomplete,
    ),
    Rule(
      builtin_rule("computation-missing-attester"),
      Info,
      check_computation_missing_attester,
    ),
    Rule(builtin_rule("frontmatter-unknown-key"), Info, check_unknown_keys),
    Rule(builtin_rule("index-frontmatter-key"), Warning, check_root_index_keys),
    Rule(builtin_rule("concept-not-indexed"), Warning, check_not_indexed),
    Rule(builtin_rule("index-description-drift"), Warning, check_drift),
    Rule(builtin_rule("duplicate-title"), Warning, check_duplicate_titles),
    Rule(builtin_rule("link-broken"), Warning, check_broken_links),
    Rule(builtin_rule("link-escapes-bundle"), Warning, check_escaping_links),
    Rule(
      builtin_rule("reference-unresolved"),
      Warning,
      check_unresolved_references,
    ),
    Rule(builtin_rule("stray-markdown"), Warning, check_strays),
    Rule(builtin_rule("log-not-newest-first"), Warning, check_log_order),
    Rule(builtin_rule("okf-version-unknown"), Info, check_unknown_version),
    Rule(builtin_rule("log-ignored"), Info, check_ignored_logs),
  ])
}