diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..ce8dcce --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @bsommers diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..b06f291 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,13 @@ +--- +name: Bug report +about: Something behaves wrongly or crashes +labels: bug +--- + +**Version** (`ontologic --version`): + +**Command and `.logic` input** (smallest that reproduces it): + +**Expected result:** + +**Actual result:** diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..f781eb7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Security vulnerability + url: https://github.com/bsommers/OntoLogic/security/advisories/new + about: Report security problems privately, not as a public issue. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..010024c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,11 @@ +--- +name: Feature request +about: Propose a change or addition +labels: enhancement +--- + +**Problem to solve:** + +**Proposed change:** + +**Alternatives considered:** diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..76ef396 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,6 @@ +## What and why + +## Checklist +- [ ] `stack test --ghc-options="-Wall -Werror"` passes locally +- [ ] Tests added or updated (a bug fix has a test that failed before) +- [ ] Docs and CHANGELOG updated if behaviour changed diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..f56d90c --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,14 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: monthly + - package-ecosystem: gradle + directory: / + schedule: + interval: monthly + - package-ecosystem: npm + directory: /editors/vscode + schedule: + interval: monthly diff --git a/.github/scripts/check_pending.sh b/.github/scripts/check_pending.sh new file mode 100755 index 0000000..e41872d --- /dev/null +++ b/.github/scripts/check_pending.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Fail when the Hspec log reports pending examples other than the optional mermaid (mmdc) and docker-based neo4j ones. +# Usage: check_pending.sh +set -euo pipefail +log="${1:?usage: check_pending.sh }" + +summary="$(grep -E '[0-9]+ examples?, [0-9]+ failures?' "$log" | tail -n 1 || true)" +if [ -z "$summary" ]; then + echo "ERROR: no Hspec summary line found in $log" >&2 + exit 1 +fi +echo "Hspec summary: $summary" + +total="$(echo "$summary" | grep -oE '[0-9]+ pending' | grep -oE '[0-9]+' || echo 0)" +if [ "$total" -eq 0 ]; then + echo "No pending examples." + exit 0 +fi + +# Pending items are listed as " N) description" under a "Pending:" heading, followed by +# a "# PENDING: reason" line. Keep the numbered description lines of that section. +pending="$(awk '/^Pending:/{p=1;next} /^(Failures:|Finished in)/{p=0} p && /^ +[0-9]+\) /{print}' "$log")" +unexpected="$(echo "$pending" | grep -v 'mermaid' | grep -v 'real neo4j' | grep -v '^$' || true)" +if [ -n "$unexpected" ] || [ -z "$pending" ]; then + echo "ERROR: $total pending example(s); only the optional mermaid (mmdc) and docker-based neo4j examples may be pending:" >&2 + echo "${unexpected:-$pending (could not list them; see the log)}" >&2 + exit 1 +fi +echo "Only the optional mermaid and neo4j examples are pending." diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 370f3a0..be2d31b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,28 +1,15 @@ -name: CI +name: Full gate (manual) concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +# Manual only. The full build-and-test gate is a local gate (AGENTS.md, "Pre-Push Verification +# Gate") and is deliberately not run automatically on GitHub, to conserve Actions minutes. Start +# this workflow by hand (Actions tab, "Run workflow") for a clean-room run. The automatic GitHub +# checks are docs.yml (link check) and pages.yml (site deployment). on: - push: - # Feature branches are covered by their pull_request run; also pushing them - # here ran CI twice per change (the two refs never share a concurrency group). - branches: [ main ] - paths-ignore: - - 'docs/**' - - '**.md' - - '**.svg' - - '.codegraph/**' - - 'LICENSE' - pull_request: - branches: [ main ] - paths-ignore: - - 'docs/**' - - '**.md' - - '**.svg' - - '.codegraph/**' - - 'LICENSE' + workflow_dispatch: permissions: contents: read @@ -30,7 +17,6 @@ permissions: jobs: haskell-test: name: Haskell Build & Test - if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-24.04 # standard GitHub-hosted runner: free for public repos timeout-minutes: 60 # a cold-cache stack build on a hosted runner is slow @@ -47,13 +33,16 @@ jobs: unzip -q /tmp/cvc5.zip -d /tmp/cvc5 sudo install -m 0755 "$(find /tmp/cvc5 -type f -name cvc5 | head -1)" /usr/local/bin/cvc5 } - curl -fsSL -o /tmp/vampire https://github.com/vprover/vampire/releases/download/v4.9casc2024/vampire || true - if [ -s /tmp/vampire ]; then - sudo install -m 0755 /tmp/vampire /usr/local/bin/vampire - vampire --version || true - fi + # No `|| true`: a missing Vampire must fail the job, not skip its specs silently. + curl -fsSL --retry 3 -o /tmp/vampire https://github.com/vprover/vampire/releases/download/v4.9casc2024/vampire + test -s /tmp/vampire + sudo install -m 0755 /tmp/vampire /usr/local/bin/vampire + vampire --version z3 --version cvc5 --version + command -v vampire + g++ --version | head -1 + sqlite3 --version - name: Set up JDK 17 uses: actions/setup-java@v4 @@ -71,6 +60,9 @@ jobs: # rdflib: IriSpec resolves the OWL and SHACL output with a real RDF parser (#49) pip install pydantic rdflib + - name: Check relative documentation links + run: python3 scripts/check_links.py + - name: Set up Node for the TypeScript check uses: actions/setup-node@v4 with: @@ -113,29 +105,33 @@ jobs: # Every stack call in this workflow (both jobs) passes the same # --ghc-options: stack recompiles the package whenever they change, and # the two jobs share one .stack-work cache. - - name: Install Stack dependencies & Build + - name: Install Stack dependencies run: | - stack build --test --no-run-tests --ghc-options="-Wall -Werror" + stack build --test --no-run-tests --only-dependencies - name: Warm Gradle dependencies for Java validation smoke test run: | chmod +x gradlew ./gradlew :models-java:compileJava - - name: Run Haskell Test Suite + # One test run does three jobs: -Wall -Werror build, the HPC coverage gate + # (scripts/check_coverage.sh, threshold 74%), and the pending-example check. + - name: Run Haskell test suite with coverage gate env: # Turn a missing toolchain into a failure: the generated-code checks in # CompileSpec must actually run here, not silently report PENDING. This covers - # go, rustc, pydantic, npm, d2 and rdflib — the ones installed above. The genuinely - # optional checks (mmdc, which pulls chromium, and the neo4j service) use - # withOptionalTool and always skip when absent. + # go, rustc, pydantic, npm, d2 and rdflib. The genuinely optional check + # (mmdc, which pulls chromium) uses withOptionalTool and always skips. ONTOLOGIC_REQUIRE_TOOLCHAINS: '1' run: | - stack test --ghc-options="-Wall -Werror" + set -o pipefail + scripts/check_coverage.sh --ghc-options="-Wall -Werror" 2>&1 | tee "$RUNNER_TEMP/hspec.log" + + - name: Fail on unexpected pending examples + run: .github/scripts/check_pending.sh "$RUNNER_TEMP/hspec.log" java-gradle-test: name: Java & Gradle Verification - if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-24.04 # standard GitHub-hosted runner: free for public repos timeout-minutes: 45 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..e038d15 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,29 @@ +name: Docs + +# The only automatic check on GitHub besides the Pages deployment. It needs no Haskell, Java or +# solver. The full build-and-test gate is local; see ci.yml (manual) and AGENTS.md. +on: + pull_request: + push: + branches: [ main ] + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + docs: + name: docs + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Check out repository + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Check relative documentation links + run: python3 -I scripts/check_links.py diff --git a/.gitignore b/.gitignore index 80f6aeb..5b03ef6 100644 --- a/.gitignore +++ b/.gitignore @@ -21,7 +21,8 @@ models-java/src/generated/ .hpc/ -# Private planning/session notes (kept locally, not published) +# Private planning/session notes (not published). Files already tracked stay tracked; +# new files here need `git add -f`. See .planning/STATE.md. .planning/ .agents/ agy-evaluation/ diff --git a/.issues/draft-2026-09-19.sh b/.issues/draft-2026-09-19.sh deleted file mode 100755 index e1f8cbd..0000000 --- a/.issues/draft-2026-09-19.sh +++ /dev/null @@ -1,788 +0,0 @@ -#!/usr/bin/env bash -# Draft issues from a code review of OntoLogic (main @ 064530a). Nothing is filed unless you pass --file. -# -# ./.issues/draft-2026-09-19.sh # dry run: print every issue -# ./.issues/draft-2026-09-19.sh --file # create them with gh (after review) -# REPO=owner/name ./.issues/draft-2026-09-19.sh --file -# -# Index (severity order): -# 1. [bug, critical] :unsat reports success on solver failure; solver errors print empty -# 2. [bug, major] Superclass bounds ignored by linter and :unsat; empty subclasses pass -# 3. [bug, major] SMT solver drops FOL axioms; :prove disproves subsumptions axioms state -# 4. [bug, major] Axiom with (and (C x) ...) antecedent applied to every C instance -# 5. [bug, major] Predicate names starting with a keyword fail to parse (e.g. orderedBy) -# 6. [bug, major] Cyclic inheritance hangs REPL :emit/:ir and LSP hover forever -# 7. [bug, major] LSP framing counts chars not bytes; non-ASCII text desyncs the server -# 8. [bug, major] Misspelled or incomplete def-* forms silently parsed as axioms -# 9. [bug, major] SMT-LIB output invalid for small/large floats and reused relation names -# 10. [bug, major] Go/Rust/Python output fails to compile; Zod drops inherited bounds -# 11. [bug, major] Neo4j/Mermaid/D2/GraphQL/OpenAPI output unloadable for stdlib ontologies -# 12. [bug, major] LSP flags valid stdlib imports as undeclared; all diagnostics on line 0 -# 13. [security, major] VS Code SMT commands shell-inject file paths/settings; wrong CLI path -# 14. [bug, major] Stdlib imports fail unless ontologic runs from the repo root -# 15. [bug, minor] capabilities.json and ontology/ bindings from 064530a are broken -# 16. [bug, major] --solve exits 0 when the solver returns unknown -# 17. [bug, minor] REPL crashes with hGetLine: end of file on Ctrl-D or piped input -# 18. [enhancement, minor] Make Acme namespace and Java package configurable -# 19. [refactor, minor] Deduplicate registry helpers and share one emit-target table -# 20. [bug, minor] ecosystem.logic models code symbols as classes; count wrong -# -# Environment for every reproduction below, unless marked [UNVERIFIED]: -# Linux, main @ 064530a, `stack build` (lts-21.25 / GHC 9.4.8), z3 and cvc5 on PATH. -set -euo pipefail - -REPO="${REPO:-}" # empty = repo of the current directory -MODE=dry-run -[[ "${1:-}" == "--file" ]] && MODE=file - -# Labels used below that the repo does not have yet (repo only has the GitHub defaults). -# Uncomment after review: -# gh label create security --color b60205 --description "Security-relevant defect" -# gh label create critical --color b60205 --description "Severity: critical" -# gh label create major --color d93f0b --description "Severity: major" -# gh label create minor --color fbca04 --description "Severity: minor" - -USED_LABELS=() - -# Fail before anything is filed if any label used below is missing from the repo. -check_labels() { - local have missing=() - have="$(gh label list ${REPO:+--repo "$REPO"} --limit 500 --json name -q '.[].name')" - for l in $(printf '%s\n' "${USED_LABELS[@]}" | sort -u); do - grep -qxF "$l" <<<"$have" || missing+=("$l") - done - if ((${#missing[@]})); then - echo "Missing labels: ${missing[*]}. Create them or edit this script." >&2 - exit 1 - fi -} - -# issue "" "<label>,<label>" <<'BODY' ... BODY -issue() { - local title="$1" labels="$2" body - body="$(cat)" - if [[ $MODE == collect ]]; then - IFS=, read -ra l <<<"$labels" - USED_LABELS+=("${l[@]}") - elif [[ $MODE == file ]]; then - gh issue create ${REPO:+--repo "$REPO"} --title "$title" --label "$labels" --body "$body" - else - printf '=== %s [%s]\n%s\n\n' "$title" "$labels" "$body" - fi -} - -# ---- Issues (edit below) ---- -all_issues() { - -issue ":unsat reports success on solver failure; solver errors print empty" "bug,critical" <<'BODY' -## Summary -When a solver is missing or fails, `:unsat` and the VS Code "Check Concept Satisfiability" command report success. Other solver errors reach the user as empty or misleading text. - -## Description -**Steps to reproduce** -1. `printf ':load examples/smart_factory.logic\n:unsat\n:solve\n:quit\n' | env PATH=/usr/bin:/bin stack exec ontologic-exe -- --repl` -2. With z3 and cvc5 installed, run `ontologic-exe -i f.logic --solve` on any input that makes Z3 fail. Example: `(forall (x) (implies (V x) (lt p 0.001)))` with `p` declared `Double` (see the invalid SMT-LIB issue). - -**Expected:** `:unsat` reports that no solver could run. Solver errors show the solver's own message. - -**Actual:** -- Step 1: `:unsat` prints `✅ All concepts are satisfiable (0 empty concepts)`. `:solve` in the same session prints `No compatible SMT solver found in PATH`. -- Step 2 with `-p z3`: `❌ SMT Solver Error: Z3 exited with error code 1: `, with nothing after the colon. -- Step 2 with the default `auto` prover: `No compatible SMT solver found in PATH (tried z3, cvc5, vampire). Please install Z3 or CVC5.`, even though both are installed. - -**Evidence** -- `src/Solver.hs:211`: `checkSingleClassSatisfiability` maps `Left _ -> return False`, so a failed run counts as "satisfiable". -- `editors/vscode/src/extension.ts:91` shows a success toast when stdout contains `0 empty concepts`. -- `src/Solver.hs:72-100`: on a non-zero exit, `runProver` reports `stderr`. z3 and cvc5 write errors to stdout. -- `src/Solver.hs:104-117`: `AutoProver` falls through on any `Left`, including real solver errors. -- `src/Main.hs:85-89`: an unknown `--prover` value (e.g. `z4`) silently becomes `auto`. -- `src/Main.hs:94`: `Unknown` exits 0. - -## Why it matters -Anyone using `:unsat` without a solver, or with an input the solver rejects, gets a false "verified" result, and CI or editor users will trust it. When the solver does report an error, users are told to install tools they already have and never see the real message. - -## Suggested fix -Suggestion: -- `checkSingleClassSatisfiability :: ... -> IO (Either String Bool)` and `findUnsatConceptsWith :: ... -> IO (Either String [String])`. Print the error in the REPL. -- Include stdout in error text. -- In `auto`, fall back to the next solver only when the executable is missing (an `IOException` of the does-not-exist kind). -- Reject unknown `--prover` values, and exit non-zero on `Unknown`. -- Optional: run every per-class check in one solver process with `(push)`/`(pop)` or `check-sat-assuming`. Today it starts one process per class: `ecosystem.logic` takes about 11.6 s for 935 classes with Z3. - -Tests: stub `PATH` with no solvers, then assert that `:unsat` reports an error. Feed an invalid SMT string and assert the error text contains the solver's message. - -## Acceptance criteria -- [ ] `:unsat` with no solver on PATH reports an error, not success -- [ ] Solver error text includes the solver's stdout diagnostics -- [ ] `auto` with z3 installed but failing reports the Z3 error, not "no solver found" -- [ ] `--prover z4` exits non-zero with a usage error -- [ ] The VS Code command shows success only on an explicit success result - -_Source: code review (xhigh) of main @ 064530a; reproduced locally_ -BODY - -issue "Superclass bounds ignored by linter and :unsat; empty subclasses pass" "bug,major" <<'BODY' -## Summary -Numeric bounds declared on a superclass are never combined with a subclass's bounds. A subclass that can have no instances passes both the linter and `:unsat`. - -## Description -**Steps to reproduce** -```lisp -(def-concept Vessel) -(def-concept Tank Vessel) -(def-property capacity Vessel Integer) -(forall (x) (implies (Vessel x) (gt capacity 10))) -(forall (x) (implies (Tank x) (lt capacity 5))) -``` -1. `ontologic-exe -i f.logic -t lint` -2. REPL: `:load f.logic` then `:unsat` - -**Expected:** `Tank` is reported as contradictory (capacity > 10 and < 5). -**Actual:** `✅ Logic Validated successfully.` and `✅ All concepts are satisfiable (0 empty concepts)`. - -**Evidence** -- `src/IR.hs:65`: `getLocalConstraints name axs` uses only the class's own name. -- `src/IR.hs:119`: an inherited property carries only the subclass's own bounds. -- `src/Solver.hs:196-205`: each class gets its own function (`Tank_capacity`, `Vessel_capacity`), with nothing linking them. -- `src/Linter.hs:170`: `checkConceptAxioms` groups bounds by concept only. - -## Why it matters -Finding concepts that refinement makes empty is the stated purpose of `:unsat` and the cross-axiom linter, and this is the most common way to produce one. The emitters then generate subclasses that can never validate. For example, the Java subclass getter gets `@Max(4)` while the parent getter has `@Min(11)`. - -## Suggested fix -Suggestion: when compiling a class, merge the bounds of the class and every ancestor per property, using a cycle-safe `getAncestors`. Use the merged set in the linter, the SMT per-class check, and the emitters. Add the repro above as a Linter and Solver test. - -## Acceptance criteria -- [ ] The repro fails lint with a cross-level contradiction message -- [ ] `:unsat` lists `Tank` -- [ ] Emitters include the parent's bounds on the subclass -- [ ] Regression tests in `test/SolverSpec.hs` and the linter spec - -_Source: code review (xhigh) of main @ 064530a; reproduced locally_ -BODY - -issue "SMT solver drops FOL axioms; :prove disproves subsumptions axioms state" "bug,major" <<'BODY' -## Summary -The SMT encoding leaves out every FOL axiom. Subsumption proofs contradict the ontology, and `--solve` reports "logically consistent" for logic the solver never saw. - -## Description -**Steps to reproduce** -```lisp -(def-concept Animal) -(def-concept Dog) -(forall (x) (implies (Dog x) (Animal x))) -``` -REPL: `:load f.logic` then `:prove Dog Animal`. - -**Expected:** `✅ Theorem Proved`. -**Actual:** `❌ Theorem Disproved ... 'Dog' is NOT subsumed by 'Animal'`, followed by a "counterexample". - -**Evidence:** `emitSMTBase` (`src/Solver.hs:219-231`, and the copy in `src/Emitters/SMT.hs:7-28`) emits only: -- class constants -- `subClassOf` facts from `def-concept` parents -- per-class numeric bounds -- relation facts - -Axioms in `irUnmappedAxioms` are dropped: implications between concepts, disjointness written with `not`, `exists`, `iff`, and relation axioms. The solver can only ever find numeric bound conflicts, and the linter already rejects those before `--solve` runs (`src/Main.hs:73-77`), so `--solve` effectively always prints "consistent". - -## Why it matters -The README advertises consistency checking and taxonomic subsumption proofs. Any ontology whose hierarchy is defined by axioms gets wrong answers, and "consistent" is reported without the logic being checked. - -## Suggested fix -Suggestion: -- Encode concepts as unary predicates over `Entity`, relations as binary predicates, and properties as functions. -- Translate FOL structurally (ForAll, Exists, Implies, And, Or, Not, Iff). -- Prove A ⊑ B by checking that `(exists ((x Entity)) (and (A x) (not (B x))))` is unsat. - -Until then, print the axioms that were not translated (as `warnUnmappedAxioms` does) and stop claiming "logically consistent". - -Tests: -- the Dog/Animal repro -- a disjointness axiom that makes a concept empty - -## Acceptance criteria -- [ ] `:prove Dog Animal` succeeds for the repro -- [ ] Axioms are included in, or explicitly reported as missing from, `--solve` output -- [ ] SolverSpec covers subsumption defined by an axiom - -_Source: code review (xhigh) of main @ 064530a; reproduced locally_ -BODY - -issue "Axiom with (and (C x) ...) antecedent applied to every C instance" "bug,major" <<'BODY' -## Summary -A conditional axiom such as `(implies (and (Tank x) (Military x)) ...)` is applied to every `Tank`. The linter then reports false contradictions, and the emitters generate wrong validators. - -## Description -**Steps to reproduce** -```lisp -(def-concept Tank) (def-concept Civil) (def-concept Military) -(def-property capacity Tank Integer) -(forall (x) (implies (and (Tank x) (Civil x)) (lt capacity 50))) -(forall (x) (implies (and (Tank x) (Military x)) (gt capacity 100))) -``` -`ontologic-exe -i f.logic -t lint` - -**Expected:** passes, because the two bounds apply to different subsets. -**Actual:** `Cross-axiom contradiction on Tank.capacity: gt 100 and lt 50`, exit 1. No target can be generated. - -**Evidence** -- `src/OntoLogic.hs:176`: `matchesConcept (And p1 p2) = matchesConcept p1 || matchesConcept p2`. `matchesConcept` also ignores which variable the predicate uses. -- The same data feeds the IR bounds used by Java, Pydantic, Zod, JSON Schema, SHACL and the Neo4j audits. -- `isUnmappedAxiom` (`src/IR.hs:141-150`) reports these same axioms as "could not be mapped". - -## Why it matters -Valid ontologies are rejected. Where there is no conflict, generated validators enforce a constraint on every instance that was meant for a subset. - -## Suggested fix -Suggestion: accept only antecedents that are exactly `(C v)`, where `v` is the quantified variable. That is the same rule as `isSimpleConceptMembership`. Leave conjunctive antecedents in `irUnmappedAxioms`. Add the repro as a linter and IR test. - -## Acceptance criteria -- [ ] The repro lints cleanly -- [ ] No bound from a conjunctive antecedent reaches `compConstraints` -- [ ] The unmapped-axiom warning and the IR agree - -_Source: code review (xhigh) of main @ 064530a; reproduced locally_ -BODY - -issue "Predicate names starting with a keyword fail to parse (e.g. orderedBy)" "bug,major" <<'BODY' -## Summary -DSL keywords are matched without a word boundary. Any predicate whose name starts with `or`, `and`, `not`, `iff`, `implies`, `forall` or `exists` gives a parse error. - -## Description -**Steps to reproduce** -```lisp -(def-concept Order) -(def-relation orderedBy Order Order) -(forall (x) (implies (Order x) (orderedBy x x))) -``` -`ontologic-exe -i f.logic -t lint` - -**Expected:** parses. -**Actual:** `3:35: unexpected 'd' expecting '('`. - -**Evidence:** `src/Parser.hs:143` has `try (symbol "or")`, and `symbol = L.symbol sc` (line 20) does not check for a word boundary. `or` is consumed from `orderedBy`, and the `parens` that follows fails after consuming input, so megaparsec never tries `parsePredicate`. The same happens for names like `origin`, `organizes`, `notifies`, `android` and `existsIn`. - -## Why it matters -Relation names are conventionally lowerCamelCase, so this hits ordinary vocabularies. The error message does not explain the cause, and the workaround is renaming domain terms. - -## Suggested fix -Suggestion: add `keyword w = lexeme (try (string w <* notFollowedBy (alphaNumChar <|> oneOf "_:-")))` and use it for every DSL keyword, including `def-*`, `import` and `namespace`. Add parser tests for `orderedBy`, `notifies` and `android`. - -## Acceptance criteria -- [ ] The repro parses -- [ ] ParserSpec covers predicates prefixed by each keyword - -_Source: code review (xhigh) of main @ 064530a; reproduced locally_ -BODY - -issue "Cyclic inheritance hangs REPL :emit/:ir and LSP hover forever" "bug,major" <<'BODY' -## Summary -`getAncestors` has no cycle detection. Compiling a registry that has an inheritance cycle loops forever, which freezes the REPL and the language server. - -## Description -**Steps to reproduce** -```lisp -(def-concept A B) -(def-concept B A) -(def-concept C) -(def-property w C Integer) -``` -1. REPL: `:load f.logic` (prints "2 lint warnings"), then `:emit python`. -2. LSP: open the file, then hover over `A`. - -**Expected:** an error or a lint message. -**Actual:** -- REPL: `:emit python` never returns (killed by `timeout 10`, exit 124). `:ir`, `:solve` and `:unsat` behave the same. -- LSP: the server writes `Content-Length: ` and hangs. Its loop is single-threaded, so every feature stops until restart. - -**Evidence:** `src/OntoLogic.hs:187-192` walks parents with no visited set. `isInherited` (`src/IR.hs:119`) runs `elem` over that infinite list, which only terminates if the searched domain is on the cycle. The CLI is safe only because `Main` exits on lint errors; REPL `:load`, REPL input and LSP `updateDoc` keep the registry anyway. - -## Why it matters -One typo in the editor kills all language features. REPL users lose their session. - -## Suggested fix -Suggestion: make `getAncestors` stop when it revisits a concept, using a `Set`. Optionally skip `compileRegistry` in the REPL and LSP when lint reports a cycle. Add a test that `compileRegistry` terminates on the repro. - -## Acceptance criteria -- [ ] `compileRegistry` terminates on cyclic input -- [ ] REPL `:emit` and LSP hover respond for the repro -- [ ] Regression test in IRSpec - -_Source: code review (xhigh) of main @ 064530a; reproduced locally_ -BODY - -issue "LSP framing counts chars not bytes; non-ASCII text desyncs the server" "bug,major" <<'BODY' -## Summary -The LSP server treats `Content-Length` as a character count, but the protocol defines it as a UTF-8 byte count. Any non-ASCII text makes the server read or send the wrong amount and lose messages. - -## Description -**Steps to reproduce:** send `didOpen` over stdio with text `"; café ⊑ comment\n(def-concept Tank)\n"`, then send a `hover` request. - -**Expected:** a diagnostics notification, then a hover response. -**Actual:** no diagnostics until the hover message arrives. The server takes the start of the hover message as the rest of the `didOpen` body, and the hover request is never answered. Reproduced with a Python stdio harness. - -**Evidence** -- `src/LSP.hs:57-62`: `readContent` reads `n` `Char`s with `getChar`. -- `src/LSP.hs:68-71`: `sendResponse` writes `length body`, which counts characters. Parse-error diagnostics quote the source line (`errorBundlePretty`), so non-ASCII in that line makes outbound lengths wrong too. - -Related, from the code: -- `getLineSafe` throws at EOF. -- `exit` is not handled. -- Unknown requests never get a response. -- JSON with a space after the colon (`"method": "x"`) is ignored. This was seen in the harness. -- [UNVERIFIED] Under `LANG=C`, `getChar` may throw on non-ASCII bytes. - -## Why it matters -Every user with a non-ASCII comment or label, including the ⊑ notation the README uses, gets a broken language server and silently dropped requests. - -## Suggested fix -Suggestion: -- Use `hSetBinaryMode stdin/stdout True`, read the body with `Data.ByteString.hGet stdin n`, and decode UTF-8. -- Write `BS.length (encodeUtf8 body)` as the length. -- Handle EOF and `exit`. -- Parse JSON with `aeson`, or adopt the `lsp` package. - -Add an LSPSpec case with multi-byte content that checks the framing. - -## Acceptance criteria -- [ ] Non-ASCII documents open and get diagnostics, and later requests are answered -- [ ] Outbound `Content-Length` equals the UTF-8 byte length -- [ ] The server exits cleanly on EOF or `exit` - -_Source: code review (xhigh) of main @ 064530a; reproduced locally with a stdio harness_ -BODY - -issue "Misspelled or incomplete def-* forms silently parsed as axioms" "bug,major" <<'BODY' -## Summary -A typo such as `(def-concpt X)`, or a `def-property`/`def-relation` missing an argument, parses as a bare predicate axiom. The definition then disappears from every output with no error. - -## Description -**Steps to reproduce** -```lisp -(def-concept Tank) -(def-concpt Typo) -(def-property capacity Tank) ; missing range type -(def-relation ownedBy Tank) ; missing range -``` -`ontologic-exe -i f.logic -t lint`, then REPL `:ir`. - -**Expected:** a parse error that names the malformed form. -**Actual:** `✅ Logic Validated successfully.` `:ir` shows `irUnmappedAxioms = [Predicate "def-concpt" [..], Predicate "def-property" [..], Predicate "def-relation" [..]]`. - -**Evidence:** `src/Parser.hs:40-49`. Each `def-*` parser is wrapped in `try`, and `IAxiom <$> parseFOL` catches everything else. - -## Why it matters -A typo silently removes concepts, fields or relations from every generated artifact. Nothing points at the typo. - -## Suggested fix -Suggestion: commit once a `def-*` keyword has matched, so the error names the missing argument. Reject predicate heads that start with `def-` or are reserved words. Optionally, lint that each axiom's predicate head is a declared concept, a declared relation, or a comparison operator. Add parser tests for each malformed form. - -## Acceptance criteria -- [ ] Each line in the repro produces a positioned parse error -- [ ] Valid axioms still parse - -_Source: code review (xhigh) of main @ 064530a; reproduced locally_ -BODY - -issue "SMT-LIB output invalid for small/large floats and reused relation names" "bug,major" <<'BODY' -## Summary -The SMT emitter writes floats in Haskell `show` format and declares a relation once per `def-relation`. Z3 and cvc5 reject the output for ordinary inputs. - -## Description -**Steps to reproduce** -1. `(def-concept Vuln) (def-property epss Vuln Double) (forall (x) (implies (Vuln x) (lt epss 0.001)))`, then `-t smt` and `--solve -p z3`. -2. `(def-concept Engine) (def-concept Car) (def-concept Wheel) (def-relation partOf Engine Car) (def-relation partOf Wheel Car)`, then `--solve -p z3`. - -**Expected:** valid SMT-LIB and a SAT result. -**Actual:** -1. Emits `(assert (< (Vuln_epss Vuln) 1.0e-3))`. Z3 reports `unknown constant e-3`; cvc5 reports `Symbol 'e-3' not declared`. Values of 1e7 and above are printed the same way. -2. Emits `(declare-fun partOf ...)` twice, and the solver fails with a duplicate declaration. The linter allows this input because its duplicate key is (name, domain, range). - -**Evidence** -- `valueToString` (`src/OntoLogic.hs:90`) is used by `emitPropertyAssertion` in both `src/Solver.hs:259-272` and `src/Emitters/SMT.hs:56-69`. -- `emitRelationDeclaration` is at `src/Solver.hs:274-280` and `src/Emitters/SMT.hs:71-78`. -- `Solver.hs` duplicates the whole SMT emitter line for line. - -## Why it matters -Probability and score bounds, such as EPSS in `stix_cve.logic`, and any relation shared across domains cannot be checked. This also triggers the misleading error reporting described in the ":unsat reports success on solver failure" issue. - -## Suggested fix -Suggestion: -- Print SMT reals as plain decimals (`showFFloat Nothing`, or `Data.Scientific`). -- Declare each relation name once and assert one fact per domain/range pair. -- Make `Solver.hs` call `Emitters.SMT` so the fix is made in one place. - -Tests: emit both repros and run `z3 -in` on the output. - -## Acceptance criteria -- [ ] Both repros produce SMT that z3 and cvc5 accept -- [ ] `Solver.hs` reuses `Emitters.SMT` instead of a copy -- [ ] SMTSpec covers a decimal like 0.001 and a reused relation name - -_Source: code review (xhigh) of main @ 064530a; reproduced locally_ -BODY - -issue "Go/Rust/Python output fails to compile; Zod drops inherited bounds" "bug,major" <<'BODY' -## Summary -Generated models do not compile or import for three common ontology shapes: pure taxonomies (Go), three-level hierarchies (Rust) and relations (Python). The TypeScript/Zod output compiles but silently drops constraints. - -## Description -**Steps to reproduce** -1. `ontologic-exe -i ontologic-lib/bfo_2020.logic -t go -o out`, then `go vet out/models.go`. -2. With `Vessel ⊃ Tank ⊃ FuelTank`, `(def-property capacity Vessel Integer)`, a `FuelTank` bound `(gt capacity 100)`, `(def-relation ownedBy Vessel Person)` and `(def-relation manages Person Person)`, emit `-t rust`, `-t python` and `-t ts`. - -**Actual** -- **Go:** `"fmt" imported and not used`. `src/Emitters/Go.hs:14` always imports fmt, but only constraint checks use it. -- **Rust:** `error[E0609]: no field capacity on type Tank` (rustc). `src/Emitters/Rust.hs:59-61` always reads `self.base.<field>`, which is wrong when the property is declared on a grandparent. -- **Python:** `ownedBy: Person` appears before `Person` is defined, and `manages: Person` appears inside `Person`. On Python 3.10, a plain class with this shape raises `NameError: name 'Person' is not defined` (checked). [UNVERIFIED with pydantic installed.] 3.14 works because annotations are evaluated lazily. CI uses 3.11. `Optional, List` are imported but unused. -- **TypeScript:** `FuelTankSchema = TankSchema.extend({})`. `src/Emitters/TypeScript.hs:19` filters out inherited properties that carry constraints, so `capacity > 100` is never enforced. Java, Python, JSON Schema and OpenAPI keep it. - -## Why it matters -The README promises compilable, validating models for every target. These failures hit the most common shapes, so users hit them on their first real ontology. - -## Suggested fix -Suggestion: -- **Go:** emit `import "fmt"` only when it is used. -- **Rust:** use `compOriginClass` to walk up to the class that declares the property and emit one `.base` per level. -- **Python:** add `from __future__ import annotations` and call `Model.model_rebuild()` for each class at the end of the file. -- **TypeScript:** emit inherited constrained properties in `.extend({...})`. - -Add tests that compile the output: `go vet`, `rustc --crate-type lib`, `python -c 'import models'`, `tsc --noEmit`. - -## Acceptance criteria -- [ ] bfo_2020 Go output passes `go vet` -- [ ] The Rust output for the three-level repro compiles -- [ ] The Python output imports on 3.11 with pydantic v2 -- [ ] Zod enforces the subclass bound -- [ ] Compile or import checks run in CI - -_Source: code review (xhigh) of main @ 064530a; reproduced locally (go vet, rustc, python3.10)_ -BODY - -issue "Neo4j/Mermaid/D2/GraphQL/OpenAPI output unloadable for stdlib ontologies" "bug,major" <<'BODY' -## Summary -The graph, diagram and API-schema emitters produce output their tools reject, especially for the namespaced names (`bfo:`, `sys:` and so on) the standard library uses. - -## Description -**Steps to reproduce:** emit `-t neo4j`, `-t mermaid`, `-t d2` and `-t graphql` for `ontologic-lib/ecosystem.logic`, and `-t neo4j` for any file with two or more concepts. - -**Actual** -- **Neo4j** (`src/Emitters/Neo4j.hs:16-35`): - - Every block reuses the variables `n`, `p`, `s` and `t`, with no `;` until the first `CREATE CONSTRAINT`. The whole nodes-and-relationships section, plus the first constraint, is therefore one statement. [UNVERIFIED against a Neo4j instance; Cypher does not allow re-binding `n` in `MERGE`, and schema and data commands cannot share a statement.] - - Namespaced labels are not backticked, so `FOR (n:bfo:Entity)` reads as two labels. - - The checked-in `examples/*.cypher` files no longer match the emitter's output. -- **Mermaid / D2** (`src/Emitters/Mermaid.hs:15-28`, `src/Emitters/D2.hs:16-30`): identifiers are emitted raw, e.g. `class sys:InformationArtifact` (seen in output). `:` is not valid in a Mermaid class id and is D2's key separator. [UNVERIFIED with mmdc/d2 installed.] `sanitizeIdent` exists for exactly this, but neither emitter calls it. -- **GraphQL** (`src/Emitters/GraphQL.hs:39-43`): - - Query fields are named `map toLower cName ++ "s"`. `ecosystem.logic` has `sys:Cost`/`sys:cost` and `sys:Status`/`sys:status`, so the output contains `sys_costs` and `sys_statuss` twice each (seen in output), which makes the SDL invalid. - - Subclass types do not get their parent's fields. -- **OpenAPI** (`src/Emitters/OpenApi.hs:28-32`): a root concept with no properties emits `properties:` with no value, which YAML reads as null. That is not a valid JSON Schema `properties` object. [UNVERIFIED with a validator.] - -## Why it matters -These are the advertised graph, visual and API targets, and the standard library (BFO, CCO, ecosystem) is what users feed them first. - -## Suggested fix -Suggestion: -- **Neo4j:** end each MERGE group with `;`, or use `UNWIND`. Backtick labels and keys. -- **Mermaid:** emit `class sys_Foo["sys:Foo"]`. **D2:** quote keys. -- **GraphQL:** disambiguate names that collide, and emit parent fields or interfaces. -- **OpenAPI:** emit `properties: {}`. - -Validate the output in tests: cypher-shell `EXPLAIN`, mmdc/d2 parsing, graphql-js `buildSchema`, and an OpenAPI linter. - -## Acceptance criteria -- [ ] Neo4j output for a multi-concept file runs in cypher-shell -- [ ] Mermaid and D2 output for bfo_2020 renders -- [ ] GraphQL SDL for ecosystem.logic builds -- [ ] OpenAPI output validates - -_Source: code review (xhigh) of main @ 064530a; output inspected locally_ -BODY - -issue "LSP flags valid stdlib imports as undeclared; all diagnostics on line 0" "bug,major" <<'BODY' -## Summary -The language server lints each buffer without resolving its imports. Any file that uses the standard library shows false errors, and every diagnostic is placed on line 0. - -## Description -**Steps to reproduce:** open a file containing `(import "bfo_2020.logic")` and `(def-concept Pump bfo:Process)`. - -**Expected:** no diagnostics. The CLI (`-t lint`) passes this file when run from the repo root. -**Actual:** `Undeclared parent concept: bfo:Process referenced by Pump`, at line 0, character 0 (confirmed over stdio). - -**Evidence** (`src/LSP.hs`): -- `updateDoc` (lines 142-160) parses the buffer with `parseRegistry` and never calls the Loader. -- The parse-error position is hard-coded to `(0,0)`, and `makeLintDiag` always uses line 0. -- `findDefinitionLine` (lines 218-223) searches only the current buffer, using a substring match, so `Tank` can jump to `(def-concept TankTruck`. - -## Why it matters -Every example, `ontology/component.logic` and `ecosystem.logic` show red errors. Users learn to ignore diagnostics, and completion and hover miss every imported symbol. - -## Suggested fix -Suggestion: -- Resolve imports through `Loader`, relative to the document's path plus the stdlib paths, and lint the merged registry. Report only diagnostics that belong to the open document. -- Take positions from the `ParseErrorBundle` (`reachOffset`). -- Store source positions on parsed items. -- Match whole identifiers when looking up definitions. - -Add LSPSpec cases for an importing document and a parse-error position. - -## Acceptance criteria -- [ ] The repro yields no diagnostics -- [ ] Parse and lint diagnostics point at the right line and column -- [ ] Go-to-definition resolves whole identifiers, including imported ones - -_Source: code review (xhigh) of main @ 064530a; reproduced locally with a stdio harness_ -BODY - -issue "VS Code SMT commands shell-inject file paths/settings; wrong CLI path" "security,major" <<'BODY' -## Summary -The extension builds shell command strings from the file path and a workspace setting. It also derives a CLI binary name that stack builds do not produce. - -## Description -**Evidence** -- `editors/vscode/src/extension.ts:55`: ``cp.exec(`"${cliPath}" -i "${filePath}" -t solve --prover=${prover}`)`` -- `editors/vscode/src/extension.ts:85`: ``cp.exec(`printf ":load ${filePath}\\n:unsat\\n:quit\\n" | "${cliPath}" --repl`)`` - -Consequences: -- A `.logic` file whose name contains `$(...)` or `"` runs shell code when either command is used. A `%` in the path breaks the `printf` form. [UNVERIFIED: not executed; follows from the code.] -- `ontologic.solver.prover` is inserted into the command unquoted. A value like `auto; <cmd>` in `.vscode/settings.json` runs `<cmd>`. [UNVERIFIED that VS Code passes non-enum values through unchanged.] -- `ontologic.lsp.path` has no `scope`, and the manifest does not declare `capabilities.untrustedWorkspaces`. -- `cliPath = lspPath.replace(/ontologic-lsp$/, 'ontologic')`, but `package.yaml` builds the CLI as `ontologic-exe`. Only the release tarball renames it. The stack candidate `.stack-work/install/x86_64-linux/bin` does not exist; the local build installed to `.stack-work/install/x86_64-linux-tinfo6/<hash>/9.4.8/bin`. -- A zero exit is shown as "Satisfiable & Consistent", including `Unknown` results. - -## Why it matters -Opening a repository with crafted file names or settings and running an OntoLogic command can execute arbitrary code. Separately, both SMT commands fail for developers using the documented `stack` workflow. - -## Suggested fix -Suggestion: -- Use `cp.execFile(cli, ['-i', filePath, '-t', 'solve', '--prover', prover])` and check `prover` against the allowed values. -- Run the REPL with `execFile` and write commands to stdin, or add a `--unsat` CLI flag. -- Set `"scope": "machine"` on the binary-path settings and declare `untrustedWorkspaces`. -- Add an `ontologic.cli.path` setting with fallbacks `ontologic` then `ontologic-exe`. -- Treat only an explicit SAT result as success. - -## Acceptance criteria -- [ ] No `cp.exec` with interpolated strings remains -- [ ] A file named `a$(touch x).logic` does not create `x` -- [ ] The SMT commands work with a `stack build` checkout - -_Source: code review (xhigh) of main @ 064530a; static analysis of extension.ts_ -BODY - -issue "Stdlib imports fail unless ontologic runs from the repo root" "bug,major" <<'BODY' -## Summary -The loader looks for `ontologic-lib/` in the current working directory, so standard-library imports fail from any other directory. - -## Description -**Steps to reproduce** -1. Create `pump.logic` containing `(import "bfo_2020.logic")` and `(def-concept Pump bfo:Process)`, outside the repo. -2. From that directory, run `ontologic-exe -i pump.logic -t lint`. -3. From the repo root, run the same command with the file's absolute path. - -**Expected:** both resolve the import. -**Actual:** step 2 prints `Import not found: bfo_2020.logic` (exit 1). Step 3 passes. - -**Evidence:** `src/Loader.hs:21-22`: `doesDirectoryExist "ontologic-lib"` checks the current directory, which is also always a search path, so a file with the same name there can shadow a stdlib file. HOW_TO_USE installs only the binary into `/usr/local/bin`. - -## Why it matters -"Automatic standard library lookup" only works inside the source checkout. Installed users, REPL `:load` from other directories, and the VS Code commands all fail on the first import. - -## Suggested fix -Suggestion: search, in order: -1. the importing file's directory -2. `$ONTOLOGIC_PATH` -3. a `--lib-path` flag -4. `<exe dir>/../ontologic-lib` (via `getExecutablePath`) -5. the cabal data dir (`data-files: ontologic-lib/*.logic` plus `Paths_ontologic.getDataDir`) - -Add a loader test that runs from a temporary directory. - -## Acceptance criteria -- [ ] The repro resolves from any working directory with the release layout -- [ ] Stdlib location is configurable -- [ ] The current directory no longer shadows imports implicitly - -_Source: code review (xhigh) of main @ 064530a; reproduced locally_ -BODY - -issue "capabilities.json and ontology/ bindings from 064530a are broken" "bug,minor" <<'BODY' -## Summary -The capability manifest and component ontology added in 064530a name a nonexistent Python entrypoint and test command, import a missing file, and contradict each other. - -## Description -- **`docs/capabilities.json`** declares `"entrypoints": {"python": "OntoLogic.core"}` and `"test_command": "pytest test/ -q"`. There is no Python package, and `test/` is Hspec, so `pytest test/ -q` prints `no tests ran` and exits 5 (checked). -- **`ontology/component.logic:6`** imports `"factory_domain.logic"`, which is not in the repo or the stdlib. `ontologic-exe -i ontology/component.logic -t lint` fails with `Import not found: factory_domain.logic`. -- **The .logic and .ttl files disagree.** - - `component.logic` declares `OntoLogicNode` as a subclass of `dsf:SoftwareFactory`, under `http://bsommers.github.io/OntoLogic/ontology#`. - - `component_schema.ttl` declares it as an individual (`a dsf:SoftwareFactory`), under `http://bsommers.github.io/OntoLogic/`. - - The two IRIs differ, and so does the kind of thing declared. -- **`.ontology/` (from abc7c46) and `ontology/` both hold bindings.** - - `.ontology/bfo_binding.cql` uses `CREATE`, which duplicates nodes on every re-run. - - `.ontology/domain_schema.ttl` uses the prefix `bfo: <http://purl.obolibrary.org/obo/bfo.owl#>`, which does not match BFO's `BFO_nnnnnnn` IRIs. - - `ontology/bfo_binding.cql` MERGEs on the full property map, so changing `poset_tier` creates a second node. -- [UNVERIFIED] `"stratum": 50` may be meant to match `poset_tier: 20`. - -## Why it matters -Capability reconcilers and graph loaders will trust this metadata. The repo's own compiler cannot load its own component ontology. - -## Suggested fix -Suggestion: -- Set the entrypoints to `ontologic-exe` and `ontologic-lsp`, and the test command to `stack test`. -- Vendor `factory_domain.logic` or drop the import. -- Choose one IRI base and one modelling choice (class or individual) for both files. -- Remove `.ontology/` or merge it into `ontology/`. -- Use `MERGE (r:Repository {id: 'repo://OntoLogic'}) SET r += {...}`. - -## Acceptance criteria -- [ ] The manifest's test command runs the real suite -- [ ] `ontology/component.logic` lints -- [ ] One binding directory, with matching IRIs in the .logic and .ttl files - -_Source: code review (xhigh) of main @ 064530a; checked locally_ -BODY - -issue "--solve exits 0 when the solver returns unknown" "bug,major" <<'BODY' -## Summary -`ontologic-exe --solve` (and `-t solve`) prints a warning but exits 0 when the solver answers `unknown`, so CI and scripts treat an undecided check as a pass. - -## Description -In `src/Main.hs:94` (`runSolverCheck`), `Sat` exits 0, while `Unsat` and `SolverError` call `exitFailure`. `Unknown out` only prints `⚠️ SMT Solver Result: ...` and falls through to exit 0. - -**Steps to reproduce** -1. Give the solver a query it can't decide, e.g. nonlinear arithmetic that makes z3 answer `unknown`, or run with a timeout. -2. `ontologic-exe -i f.logic --solve; echo $?` - -**Expected:** a non-zero exit, preferably one distinct from UNSAT. -**Actual:** exit 0. Confirmed from the code; not run with an input that makes z3 answer `unknown`. - -## Why it matters -`--solve` is the consistency gate. Anyone using it in CI or a pre-commit hook gets a green result when nothing was proved, so inconsistent ontologies can merge without anyone noticing. - -## Suggested fix -Suggestion: in the `Unknown` branch, call `exitWith (ExitFailure 2)` or similar, and document the codes (0 = SAT, 1 = UNSAT/error, 2 = unknown). Add an Hspec or golden test that stubs the solver result and asserts the exit code. - -## Acceptance criteria -- [ ] `Unknown` yields a documented non-zero exit code -- [ ] A test covers the exit code for each `SolverResult` constructor - -_Source: code review (xhigh) of main @ 064530a; confirmed in src/Main.hs_ -BODY - -issue "REPL crashes with hGetLine: end of file on Ctrl-D or piped input" "bug,minor" <<'BODY' -## Summary -The REPL loop calls `getLine` without checking for EOF, so Ctrl-D or the end of piped input crashes it with an uncaught exception. - -## Description -**Steps to reproduce** -`printf ':help\n' | stack exec ontologic-exe -- --repl` - -**Expected:** the REPL exits cleanly (e.g. prints `Goodbye!`) with status 0. -**Actual:** after the output, `ontologic-exe: <stdin>: hGetLine: end of file` (reproduced locally), and the process ends through an uncaught IOException. - -Cause: `src/REPL.hs:56`, where `line <- getLine` runs with no `isEOF` check. - -## Why it matters -Ctrl-D is the normal way to leave a terminal REPL, and piping a script of commands into `--repl` is a natural way to automate it. Both end in a scary error message and a failure exit status. - -## Suggested fix -Suggestion: check `isEOF` before `getLine` and treat EOF like `:quit`, or switch to `haskeline`, which also gives history and line editing. Add a test that pipes a finite command list into the REPL and asserts a clean exit. - -## Acceptance criteria -- [ ] Piped input ending without `:quit` exits 0 with no exception text -- [ ] Ctrl-D in an interactive session exits cleanly - -_Source: code review (xhigh) of main @ 064530a; reproduced locally_ -BODY - -issue "Make Acme namespace and Java package configurable in OWL/SHACL/Java" "enhancement,minor" <<'BODY' -## Summary -Generated OWL, SHACL and Java output hard-codes a Acme-specific namespace and package, whatever the ontology's own `namespace` declarations say. - -## Description -Current behavior: -- `src/Emitters/Owl.hs:16-24`: `xmlns`, `xml:base` and `owl:Ontology rdf:about` are fixed to `http://www.acme.com/ontologies/fleet`. -- `src/Emitters/Shacl.hs:22`: `@prefix ont: <http://www.acme.com/ontologies/fleet#>`. -- `src/Emitters/Java.hs:8` and `src/Main.hs:105`: the Java package defaults to `com.acme.generated` (`--java-package` overrides it only on the CLI; the REPL `:emit java` can't). - -So an ontology that declares `(namespace sys "http://bsommers.github.io/ecosystem")` produces OWL and SHACL claiming its classes live under acme.com. - -## Why it matters -The IRIs in the output are wrong for every user who isn't that one project. Loading the OWL/SHACL next to other data mints identifiers in a domain the user doesn't control, and two unrelated ontologies collide under the same base IRI. - -## Suggested fix -Suggestion: -- Derive the base IRI from the registry's first/default `namespace` declaration. -- Add a `--base-iri` CLI flag (and a REPL setting) as an override. -- Use a neutral default such as `http://example.org/ontologic#` and `ontologic.generated`. -- Add golden tests asserting that the output IRIs follow the declared namespace. - -## Acceptance criteria -- [ ] OWL/SHACL base IRIs come from the ontology's namespace or a flag -- [ ] No `acme` string remains in `src/` -- [ ] The REPL can set the Java package - -_Source: code review (xhigh) of main @ 064530a; confirmed by grep_ -BODY - -issue "Deduplicate registry helpers and share one emit-target table" "refactor,minor" <<'BODY' -## Summary -`mergeRegistries`/`emptyRegistry` are defined in three places, and the CLI and REPL keep separate, already diverging lists of emit targets. - -## Description -- `emptyRegistry` is defined in `src/Parser.hs:172` and `src/Loader.hs:106`. -- `mergeRegistries` is defined in `src/Loader.hs:96` and `src/REPL.hs:195`. -- Emit targets are dispatched separately in `src/Main.hs` (`processTarget`, from line 97) and `src/REPL.hs:159-179` (`:emit`). The aliases differ (the REPL accepts `golang`, `gql`, `smtlib`, `zod`, `json`), and targets listed in the CLI help such as `mermaid` and `d2` aren't available from the REPL. - -## Why it matters -Any new `Registry` field has to be added to every copy. Missing one silently drops data in only one of the paths (loader vs REPL). New targets land in the CLI but not the REPL, and users see inconsistent behavior between the two front ends. - -## Suggested fix -Suggestion: -- Move `emptyRegistry`, `mergeRegistries` and `deduplicateRegistry` into one module (e.g. `OntoLogic` or a new `Registry` module) and import it everywhere. Deriving `Semigroup`/`Monoid` for `Registry` would do the job neatly. -- Define a single `targets :: [(String, [String], Registry -> Output)]` table (name, aliases, emitter) and use it for CLI dispatch, REPL `:emit`, and the `--target` help text. -- Add a test asserting that every target in the table works from both the CLI and the REPL. - -## Acceptance criteria -- [ ] One definition each of `emptyRegistry` and `mergeRegistries` -- [ ] The CLI and REPL accept the same targets and aliases -- [ ] The `--target` help text comes from the table - -_Source: code review (xhigh) of main @ 064530a; confirmed by grep_ -BODY - -issue "ecosystem.logic models code symbols as classes; commit count is wrong" "bug,minor" <<'BODY' -## Summary -The generated `ontologic-lib/ecosystem.logic` declares every harvested code symbol as a subclass (`def-concept`), puts every repo under one `sys:` namespace, and has 910 symbols, not the 1009 the commit message claims. - -## Description -- The file (from 6e97354, "harvest 1009 cross-ecosystem AST symbols") has 914 `def-concept` forms: 4 bridge classes plus 910 symbols, e.g. `(def-concept sys:registerPlugin sys:CodeSymbol)`. -- Each function or method name is modelled as a **class** under `sys:CodeSymbol`. In BFO terms a particular symbol is an instance of an information artifact, not a universal. So the OWL/SHACL/GraphQL output yields hundreds of meaningless types (see the GraphQL name-collision issue: `sys_costs`/`sys_statuss`). -- Every repo's symbols share the `sys:` namespace, and the source repo only survives as a `;; From uitoolbox` comment. Same-named symbols from different repos collapse into one concept. -- The 1009 vs 910 difference is unexplained; it may be deduplication or dropped symbols. [UNVERIFIED] which. - -## Why it matters -Anything downstream (graph loads, reasoning, generated code) inherits the wrong modelling, and the collapsed names lose provenance. The commit message's count can't be reproduced from the file. - -## Suggested fix -Suggestion: -- Emit symbols as individuals/instances (or as relation facts like `(definedIn registerPlugin uitoolbox)`) rather than `def-concept`. -- Qualify identifiers per repo (e.g. `sys:uitoolbox/registerPlugin`) or add a per-repo namespace. -- Make the harvester print how many symbols it harvested, deduplicated and dropped, and add a test that counts the generated forms. -- Correct the count in `docs/` and in future commit messages. - -## Acceptance criteria -- [ ] Code symbols are not declared as classes -- [ ] Each symbol records its source repo in data, not only in a comment -- [ ] The harvester's reported count matches the generated file - -_Source: code review (xhigh) of main @ 064530a; count checked with grep_ -BODY - -} - -# ---- Run ---- -if [[ $MODE == file ]]; then - MODE=collect; all_issues - check_labels - MODE=file -fi -all_issues diff --git a/AGENTS.md b/AGENTS.md index d94784e..d6e2bb9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,14 +1,16 @@ # AGENTS.md ## Repository Overview -OntoLogic is a domain-specific language compiler, semantic linter, multi-target emitter, and automated FOL/SMT reasoner for BFO (Basic Formal Ontology) and real-world industrial ontologies. Written in Haskell (GHC 9.4.8) with multi-target emitters for Java/Jakarta, Python/Pydantic, Rust, Go, TypeScript/Zod, Cypher (Neo4j), OWL, SHACL, SMT-LIB2, D2, and Mermaid. +OntoLogic is a domain-specific language compiler, semantic linter, multi-target emitter, and automated FOL/SMT reasoner for BFO (Basic Formal Ontology) and real-world industrial ontologies. Written in Haskell (GHC 9.4.8). It has 18 output targets; the authoritative list is the `targets` table in `src/Targets.hs`. -## CRITICAL DIRECTIVE: GitHub Actions CI Conservation -GitHub Actions CI quota is strictly limited. All agents and developers MUST observe: -1. **Local Test Execution First**: NEVER push branches or open PRs without running full test suites locally. -2. **No Intermediate Commits**: Do not push intermediate or broken commits to origin that trigger remote CI runs. +## CRITICAL DIRECTIVE: GitHub Actions Conservation (CI is local) +GitHub Actions minutes are strictly limited, so the full build-and-test gate is a local gate and does not run on GitHub automatically. On GitHub only two things run by themselves: the `docs` check (`.github/workflows/docs.yml`, a relative-link check via `python3 -I scripts/check_links.py`, on pull requests and pushes to `main`) and the Pages deployment (`.github/workflows/pages.yml`). The full workflow (`.github/workflows/ci.yml`, Haskell build and test plus Java/Gradle) runs only when started by hand with `workflow_dispatch`. All agents and developers MUST observe: +1. **Local Test Execution First**: NEVER push branches or open PRs without running the full gate locally. Nothing on GitHub will run it for you. +2. **No Intermediate Commits**: Do not push intermediate or broken commits to origin. 3. **Merge Gate**: Never merge pull requests or push branch deletions without explicit user authorization command. -4. **Docs Optimization**: Pure documentation, SVG, and markdown changes are ignored by CI (`paths-ignore`). +4. **Manual full run**: Start `ci.yml` by hand only when a clean-room run is really needed. + +This section is the single list of gates. `CLAUDE.md`, `GEMINI.md`, `docs/dev/README.md` and the installation guide link here instead of repeating it. ### Pre-Push Verification Gate Before pushing any branch or creating a PR, run: @@ -23,6 +25,21 @@ stack test --ghc-options="-Wall -Werror" ./gradlew :models-java:compileJava ``` +**Strict local runs.** Locally, tests that need an external toolchain (go, rustc, pydantic, npm, d2, rdflib, Vampire and so on) skip silently when the tool is missing, so a green local run can be weaker than the manual `ci.yml` run. That workflow sets `ONTOLOGIC_REQUIRE_TOOLCHAINS=1`, which turns a missing toolchain into a failure. Set it locally to get the same behaviour: +```bash +ONTOLOGIC_REQUIRE_TOOLCHAINS=1 stack test --ghc-options="-Wall -Werror" +``` + +**Coverage gate.** `scripts/check_coverage.sh` (74% threshold) is a local gate. It is not enforced automatically on GitHub; the manual `ci.yml` run executes it, and you run it yourself before every push. Also check for unexpected pending examples with `.github/scripts/check_pending.sh` on the saved hspec log. + +**Community files.** Contribution rules are in `CONTRIBUTING.md` and vulnerability reporting is in `SECURITY.md` at the repo root (both being added in v1.8.4; see `.planning/STATE.md`). + +### Release checklist +1. `CHANGELOG.md` entry; `package.yaml` and `ontologic.cabal` version; `--version` output and VS Code extension version match. +2. `.planning/STATE.md` and `.planning/ROADMAP.md` (history entry) updated; a phase or release summary written. +3. All gates above pass locally; link check (`scripts/check_links.py`) passes. +4. Tag in both repos (the private archive and the public repo). + ## Common Commands ```bash # Build compiler and REPL @@ -44,15 +61,11 @@ stack exec ontologic-exe -- -i examples/bfo_manufacturing.logic -t neo4j -o dist ``` ## Architecture Map -- `src/OntoLogic.hs`: Core AST definitions (`Registry`, `Concept`, `Property`, `Relation`, `Formula`, `Term`). -- `src/Parser.hs`: Megaparsec parser for s-expression syntax (`def-concept`, `def-property`, `def-relation`, axioms). -- `src/Linter.hs`: Semantic validations (circular inheritance, missing domains/ranges, duplicate declarations). -- `src/FOLTheory.hs`: First-Order Logic extraction, quantifier variable binding, and SMT formula translation. -- `src/Solver.hs`: Automated reasoning engine wrapping external SMT solvers (Z3, CVC5, Vampire). -- `src/Emitters/`: Target code and schema generators (`SMT.hs`, `Neo4j.hs`, `Java.hs`, `Python.hs`, etc.). +See the module map in [`docs/architecture.md`](docs/architecture.md) (section "Module map"), which is kept current. Other places: - `examples/`: Reference ontologies and checked-in artifacts (`.logic`, `.cypher`, `.mmd`, `.d2`, `.svg`). +- `test/`: Hspec suites, one per module or target, plus fixtures in `test/fixtures/`. ## Invariants & Contracts - **BFO Realism**: Separate Information Content Entities (`SoftwareCode`, GDC) from Execution (`SoftwareProcess`, Occurrent). Model trust and permissions as roles (`TrustedRole`, RealizableEntity) rather than objects. -- **Compiler Warnings**: `package.yaml` enforces `-Wall -Werror=incomplete-uni-patterns`. Avoid partial pattern matches. +- **Compiler Warnings**: `package.yaml` sets no `-Wall` flags; the warning gate is the `--ghc-options="-Wall -Werror"` argument to `stack test` above (the manual `ci.yml` run uses the same). Avoid partial pattern matches. - **Artifact Sync**: When modifying `.logic` files, run `./scripts/regenerate_examples.sh` and compile `.d2.svg` via `d2`. diff --git a/CHANGELOG.md b/CHANGELOG.md index e5f5ea9..a6c4b32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,87 @@ All notable changes to OntoLogic are recorded here. The format follows Entries before 1.5.1 were back-filled from git history. v1.4.0 and v1.5.0 were tagged after the fact, on their version-bump commits. +## [1.8.4] - Unreleased + +"Honest surface": the solver no longer reports a theory as consistent when it failed, the +linter stops rejecting satisfiable theories, and the emitters stop dropping rules silently. + +### Behaviour changes you will notice +- **Errors that used to print "consistent" now fail.** A Z3 or CVC5 `(error ...)` line, a + Vampire parse failure, or any output that is not exactly one verdict line is reported as a + solver error with a non-zero exit. Scripts that relied on exit 0 in those cases will now see + a failure. That is the intended fix. +- **Some lint findings are now warnings.** Findings from the propositional (SAT) pass are + printed as `warning:` and do not stop the run (exit 0); the language server publishes them + with warning severity. Structural findings, bound contradictions and cross-axiom concept + contradictions stay errors. + +### Fixed +- Fail closed on every backend (Z3, CVC5, Vampire, native). Vampire is given `--input_syntax + tptp`; GaveUp, ResourceOut and Timeout are "unknown". `unsat` is never read as `sat`. +- The native prover answers "unknown" (exit 2) when the theory uses equality, instead of a + verdict it cannot support. +- An empty concept is reported as such and no longer as a global contradiction (bounds are no + longer asserted on a fictitious concept constant). `:explain` checks consistency first. +- The `--solve-memory` warning is accurate and the "not sent" notice appears only on the SMT + route; very large `-T` values are clamped instead of overflowing. +- Linter: a fact about one individual is no longer read as universal; `(implies ... false)` + and `(not false)` are accepted; bounds are read only under their binder guard. `--cnf` no + longer hangs on `(not top)`. +- Conditionals written with `eq` or `ne` (string, Boolean, numeric) are enforced in Python, + Java, Rust, Go and TypeScript and carry a real premise in SHACL. No translator falls back + to `true`; what cannot be expressed is emitted as an "unmapped" comment. Conditionals on + inherited properties compile in Rust, Java and Go. A declared relation named gt, gte, lt or + lte is no longer treated as arithmetic. +- `Int` in `ontologic-lib/factory_domain.logic` and undeclared symbols in two examples. +- **A partial check is no longer reported as consistent.** When any axiom is not sent to the + solver and the rest is satisfiable, the answer is "unknown" (exit 2) with the count and the + list of axioms, in the CLI, the REPL (`:solve`, `:model`, `:explain`; a `:prove` that would + say Disproved says unknown) and the language server. UNSAT and Proved are unchanged. + `examples/security_policy.logic` now declares `AdminPanel`, which its axiom referred to. +- **The native prover now stays within `-T`.** The limit was applied afresh to the consistency + check and to every concept of the coherence sweep, so `-T 20` on a theory it cannot saturate + ran for 60 s. The limit is now one budget for the whole `--solve` run, and the prover and + clausifier modules are compiled with `-fno-omit-yields` so that a non-allocating loop + cannot defeat the timeout. + +### Changed +- Default solver time limit is 60 s when `-T` is not given (CLI, REPL, language server). +- Imports must name a `.logic` file; absolute import paths are refused unless + `--allow-absolute-imports` is given (relative `../` imports still work). +- `--version` prints `ontologic 1.8.4` and the REPL banner shows the same version; + `--neo4j-edition` rejects unknown values; an unknown REPL `:command` says so. +- Namespace rule: two different URIs for one prefix is an error; repeating the same prefix and + URI is fine. +- User guide and README corrected against behaviour; "zero schema drift" is now stated as an + aim with a link to the limitations. VS Code extension grammar and snippets rewritten. + +### Added +- New lint errors: undeclared property range or type (for example `Int`, `DateTime`) and a + namespace prefix with conflicting URIs. New warning: undeclared predicate or property inside + an axiom. +- Tests: fail-closed solver spec and fixtures, lint-soundness spec, emitter-parity spec, and a + documentation-sample spec that parses every sample in the README and user guide. +- `scripts/check_links.py` (non-zero exit on broken relative links). +- GitHub Actions: the full build-and-test workflow (`ci.yml`) is now manual-only + (`workflow_dispatch`), and the full gate stays local. A light `docs` workflow + (`docs.yml`, link check) runs on pull requests, including from forks, and on pushes to + `main`; the Pages deployment is unchanged. The manual run uses the coverage script, fails + when Vampire is missing and fails on unexpected pending examples. Adds CODEOWNERS, issue and + PR templates, dependabot. + +### Security +- Imports of non-`.logic` files are refused without echoing file contents, and absolute + import paths need an explicit flag. +- `SECURITY.md` (GitHub private vulnerability reporting), `CONTRIBUTING.md` and a code of + conduct added. The unused Dockerfile.python and requirements.txt were removed. + +### Known limitations +- Some wrong verdicts remain until the typed theory in v1.9.0 (see the soundness defects + deferred to that milestone). +- `--warn-unmapped` is not yet per target. +- SQL keeps its own comparison inversion and reports string and Boolean equality as unmapped. + ## [1.8.3] - 2026-11-11 Emitter, REPL and prover fixes found while writing the user guide, and a warning for answers @@ -168,7 +249,7 @@ Automated Theorem Prover (ATP) expansion via Vampire & TPTP FOF, PostgreSQL / AN - Hover documentation tooltips (`textDocument/hover`) showing concept parentage, attached properties, and comments. - Symbol rename refactoring (`textDocument/rename` and `prepareRename`) with workspace-wide text edits. - On-demand code formatting provider (`textDocument/formatting`). -- **Architectural Rationale Manifesto (`docs/WHY_ONTOLOGIC.md`):** +- **Architectural Rationale Manifesto (`docs/purpose.md`):** - Comprehensive manifesto detailing the 5 fatal anti-patterns in modern systems (Distributed Logic Drift, Sloppiness Tax, LLM Hallucinations, Academic OWL Trap, Data vs. Logic Contracts). - Root `README.md` and `docs/README.md` links updated. diff --git a/CLAUDE.md b/CLAUDE.md index a9c69df..064a163 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,7 +1,7 @@ # CLAUDE.md -See [AGENTS.md](AGENTS.md) for full architecture map, development workflow, and required pre-push verification gates. +See [AGENTS.md](AGENTS.md) for full architecture map, development workflow, and the single list of required pre-push verification gates. ## Directives -- **CI Conservation**: Execute `stack test --ghc-options="-Wall -Werror"` locally before pushing. Avoid redundant remote CI triggers. +- **CI is local**: Run every gate listed under "Pre-Push Verification Gate" in AGENTS.md locally before pushing (not only `stack test`). GitHub automatically runs only the `docs` link check and the Pages deployment; the full workflow (`ci.yml`) is manual-only. Do not start it without need. - **Merge Gate**: Never merge PRs without explicit user authorization command. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..ba63950 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,10 @@ +# Code of Conduct + +This project adopts the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/) +by reference. It applies in all project spaces (issues, pull requests, discussions) and to anyone +representing the project in public. + +To report unacceptable behaviour, use GitHub private vulnerability reporting +(<https://github.com/bsommers/OntoLogic/security/advisories/new>) and mark the report as a conduct +matter, or contact the maintainer through the profile at <https://github.com/bsommers>. Reports are +handled privately by the maintainers, who follow the enforcement guidelines in the Covenant. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..ff2d29b --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,40 @@ +# Contributing to OntoLogic + +Thanks for helping. Please read the [Code of Conduct](CODE_OF_CONDUCT.md) first; report security +problems as described in [SECURITY.md](SECURITY.md), not in public issues. + +## Build and test + +OntoLogic is a Haskell project built with [Stack](https://docs.haskellstack.org/). + +```bash +stack build +stack test --ghc-options="-Wall -Werror" # the full gate; run it locally before every push +``` + +Some specs call real tools (z3, cvc5, vampire, go, rustc, python3 with pydantic and rdflib, node, +d2, g++, sqlite3, javac). Locally a missing tool makes its spec report as pending. Pass +`ONTOLOGIC_REQUIRE_TOOLCHAINS=1` to turn that into a failure (the manual `ci.yml` workflow sets it). + +The full gate runs on your machine, not on GitHub. Before every push, also run: + +- `scripts/check_coverage.sh` enforces the expression-coverage floor (74%). +- `python3 -I scripts/check_links.py` fails on broken relative links in the docs. This is the one check GitHub also runs automatically (the `docs` check on pull requests). +- `./gradlew clean build test` checks the generated Java model. +- `.github/scripts/check_pending.sh <hspec-log>` fails on unexpected pending examples. + +The maintainers can start the full workflow by hand on GitHub (`ci.yml`, `workflow_dispatch`). + +## Pull requests + +- Fork the repository and open the pull request against `main`. On GitHub only the `docs` link check runs on pull requests (including from forks); the full build and test is run locally by you and by the maintainers. +- Add a test for every behaviour change; a bug fix needs a test that failed before the fix. +- Keep `-Wall -Werror` clean. Do not weaken or delete a test to make the suite pass. +- Update the docs and `CHANGELOG.md` when you change a command, flag, or behaviour. +- Keep changes focused; one concern per pull request. + +## Ontology and emitter changes + +Every file in `examples/` and `ontologic-lib/` must still lint clean. If a new check flags one, +fix the ontology rather than the check. A translator that cannot express a construct must emit an +"unmapped" comment, never silently drop it. diff --git a/Dockerfile.python b/Dockerfile.python deleted file mode 100644 index 8a7a4ed..0000000 --- a/Dockerfile.python +++ /dev/null @@ -1,5 +0,0 @@ -FROM python:3.11-slim -WORKDIR /app -COPY requirements.txt . -RUN pip install -r requirements.txt -COPY . . diff --git a/README.md b/README.md index 003467d..0294ae8 100644 --- a/README.md +++ b/README.md @@ -17,9 +17,9 @@ $$ $$/ $$ | $$ |$$ |$$ $$/ $$ |$$ $$/ $$ $$ |$$ |$$ | **Logic-as-Code compiler, ontology transpiler and SMT solver engine.** -OntoLogic is a first-order logic (FOL) domain-specific language, multi-target compiler, theorem-prover bridge and REPL written in Haskell. Write a formal ontology once, check it for consistency with Z3, CVC5 or Vampire, and compile it into code, API contracts, database schemas, knowledge-graph formats and diagrams. +OntoLogic is a first-order logic (FOL) domain-specific language, multi-target compiler, theorem-prover bridge and REPL written in Haskell. Write a formal ontology once, check it for consistency with Z3, CVC5, Vampire or the built-in native prover, and compile it into code, API contracts, database schemas, knowledge-graph formats and diagrams. The aim is that all of these outputs stay in step with the model instead of drifting apart; some axioms are not yet enforced by every output, so read [Current limitations](#current-limitations) first. -[![CI](https://github.com/bsommers/OntoLogic/actions/workflows/ci.yml/badge.svg)](https://github.com/bsommers/OntoLogic/actions/workflows/ci.yml) +[![Docs](https://github.com/bsommers/OntoLogic/actions/workflows/docs.yml/badge.svg)](https://github.com/bsommers/OntoLogic/actions/workflows/docs.yml) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) Project site: <https://bsommers.github.io/OntoLogic/> | Rationale: [docs/purpose.md](docs/purpose.md) @@ -29,6 +29,7 @@ Project site: <https://bsommers.github.io/OntoLogic/> | Rationale: [docs/purpose ```bash stack build # 1. build stack exec ontologic-exe -- -i examples/smart_factory.logic -t lint # 2. lint +stack exec ontologic-exe -- --version # prints: ontologic 1.8.4 stack exec ontologic-exe -- -i examples/smart_factory.logic -t solve # 3. check consistency (SMT) stack exec ontologic-exe -- -i examples/smart_factory.logic -t ts -o ./generated/ts # 4. emit TypeScript/Zod stack exec ontologic-exe -- --repl # 5. interactive REPL @@ -40,8 +41,8 @@ Full walkthrough: [docs/user-guide/quickstart.md](docs/user-guide/quickstart.md) - **FOL DSL** with typed properties, binary relations, quantifiers and inheritance. - **Modular namespaces**: `import`, `namespace`, cycle detection and a standard library lookup path. -- **Semantic linter**: symbol resolution, circular inheritance, duplicates and axiom contradictions. -- **Multi-prover solver**: consistency, subsumption proofs, unsatisfiable-concept detection and counterexamples (Z3, CVC5, Vampire or auto). +- **Semantic linter**: symbol resolution, circular inheritance, duplicates and axiom contradictions (structural problems are errors; findings from the logical pass are warnings). +- **Multi-prover solver**: consistency, subsumption proofs, unsatisfiable-concept detection and counterexamples (Z3, CVC5, Vampire, the built-in native prover, or auto). The solver fails closed: an error or an unclear answer is never reported as satisfiable, and every backend has a 60 second default time limit. - **Language server and VS Code extension** (`ontologic-lsp`, `editors/vscode`). - **Interactive REPL** with `:load`, `:solve`, `:prove`, `:unsat`, `:emit <target>`. - **Many emitters** from one shared intermediate representation (`ModelIR`). @@ -59,6 +60,16 @@ Select with `-t <target>`; see `--help` for the full list and [docs/user-guide/t | Diagrams | `mermaid`, `d2` (add `--render` for images); see [docs/user-guide/visualization.md](docs/user-guide/visualization.md) | | Tooling | `lint`, `repl`, `lsp` | +## Current limitations + +- Generated code enforces property bounds and simple conditional bounds. Other axioms (disjointness, existentials, relational rules) are checked by the solver, not by the generated code, and are reported as "unmapped" (use `--warn-unmapped` to list them). +- The solver encoding does not yet assert the domain and range of relations on the Z3 and CVC5 route, and ignores cardinality. +- `def-individual` feeds the solver only; no target emits individuals, and there is no way yet to check instance data against a model. +- The shipped BFO file declares categories and relations but carries almost no axioms. +- The SQL target writes each relation twice (a junction table and a `TEXT[]` column). + +Details: [targets and emitters](docs/user-guide/targets-and-emitters.md#what-is-and-is-not-enforced-or-exported) and [axioms and reasoning](docs/user-guide/axioms-and-reasoning.md). + ## Documentation - [Documentation index](docs/README.md) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c20b7e1 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,27 @@ +# Security Policy + +## Reporting a vulnerability + +Please report vulnerabilities privately through GitHub private vulnerability reporting: +open the repository's **Security** tab and choose **Report a vulnerability** +(<https://github.com/bsommers/OntoLogic/security/advisories/new>). +Do not open a public issue for a security problem. + +Include the OntoLogic version (`ontologic --version`), the `.logic` input or command line that +triggers the problem, and what you expected to happen. You can expect an acknowledgement within +a week. Fixes are released as patch versions and credited in the advisory unless you ask otherwise. + +## Scope + +In scope: the `ontologic` compiler, the `ontologic-lsp` language server, the REPL, the files in +`ontologic-lib/`, and the build and release scripts in this repository. Examples of interest: +reading files outside the intended import roots, running unintended commands, and a hostile +`.logic` file exhausting resources. + +Not in scope: a solver reporting a wrong answer for a valid ontology (file a normal bug report), +and vulnerabilities in third-party tools OntoLogic calls (Z3, cvc5, Vampire, d2, mmdc); report +those upstream. + +## Supported versions + +Only the latest release receives security fixes. diff --git a/docker-compose.yml b/docker-compose.yml index e2655a6..0b1513d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,19 +1,11 @@ -version: '3.8' +# Local Neo4j used by the optional CompileSpec test that applies generated Cypher +# (`docker compose up -d neo4j`). Bound to localhost only; the password is a local test value. services: neo4j: image: neo4j:5.12 - ports: ["7474:7474", "7687:7687"] + ports: ["127.0.0.1:7474:7474", "127.0.0.1:7687:7687"] environment: - NEO4J_AUTH=${NEO4J_AUTH:-neo4j/password} healthcheck: test: ["CMD", "cypher-shell", "RETURN 1"] interval: 10s - - validator: - build: - context: . - dockerfile: Dockerfile.python - depends_on: - neo4j: - condition: service_healthy - volumes: ["./generated/python:/app/models"] diff --git a/docs/architecture.md b/docs/architecture.md index e8adff6..ae3ddb6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -71,7 +71,9 @@ emitter or solver runs. ## Frontend and loader - **Grammar.** Top-level forms are `def-concept`, `def-property`, `def-relation`, - `def-axiom` (and bare `forall` / `exists` axioms), `namespace` and `import`. + `def-individual`, `def-axiom` (and bare `forall` / `exists` axioms), `namespace` + and `import`. Typed binders `((x Concept))`, `if` (a synonym of `implies`) and + `!=` are also accepted. Formulas use `forall`, `exists`, `implies`, `iff`, `and`, `or`, `not`, equality, comparison operators (`gt`, `gte`, `lt`, `lte`) over signed numeric literals, and strings. See the [language reference](user-guide/language-reference.md). @@ -82,11 +84,12 @@ emitter or solver runs. chain of files being visited (a repeat is reported as a circular import with the cycle spelled out) and a finished set (a diamond import is loaded once). Search order for a relative import: the importing file's directory first, then - `$ONTOLOGIC_PATH` (`:`-separated), the directory beside the binary, the package - data directory, `./ontologic-lib`, and the current directory last. Extra - directories come from the repeatable `--lib-path DIR`. Searching the current + each repeatable `--lib-path DIR`, then `$ONTOLOGIC_PATH` (`:`-separated), the + directory beside the binary, the package data directory, `./ontologic-lib`, and + the current directory last. Searching the current directory last means a stray local file cannot shadow a standard-library - module. Absolute paths bypass the search. + module. Imports must name a `.logic` file, and absolute paths are refused unless + `--allow-absolute-imports` is given. ## Core data model diff --git a/docs/dev/README.md b/docs/dev/README.md index fcdb506..ca0101a 100644 --- a/docs/dev/README.md +++ b/docs/dev/README.md @@ -13,7 +13,7 @@ Some documents are snapshots. Check the current code and | Area | Document | What it is | | :--- | :--- | :--- | | Roadmap input | [Suggested Improvements](SUGGESTED_IMPROVEMENTS.md) | Architectural review, bug audit, semantic gaps and a prioritized modernization list | -| Quality | [Test Coverage](TEST_COVERAGE.md) | Test-suite coverage audit and gap list | +| Quality | [Test Coverage](TEST_COVERAGE.md) | Test-suite coverage audit (last measured 2026-10-18) and remaining gaps | | Design notes | [Constraint considerations](design/constraint_considerations.md) | Whether to constrain FOL to Horn clauses; the profile-based architecture | | | [Constraints and patterns](design/constraints_and_patterned.md) | Logical expressiveness compared with Horn clauses, and how formulas are parsed and linted | | Reviews | [Gemini review](reviews/GEMINI_3_7_REVIEW.md) | AI-generated codebase, security and semantic-gap review with a phased roadmap | @@ -32,6 +32,7 @@ Some documents are snapshots. Check the current code and ## Before you push -The required verification gates and architecture map for contributors are in -[`AGENTS.md`](../../AGENTS.md). In short, run -`stack test --ghc-options="-Wall -Werror"` locally first. +The required verification gates (there are several, not one) and the architecture +pointer for contributors are in [`AGENTS.md`](../../AGENTS.md). Run all of them +locally first. GitHub automatically runs only the docs link check and the Pages +deployment; the full workflow (`.github/workflows/ci.yml`) is manual-only. diff --git a/docs/dev/SUGGESTED_IMPROVEMENTS.md b/docs/dev/SUGGESTED_IMPROVEMENTS.md index ef4d31a..0524e18 100644 --- a/docs/dev/SUGGESTED_IMPROVEMENTS.md +++ b/docs/dev/SUGGESTED_IMPROVEMENTS.md @@ -104,7 +104,14 @@ flowchart TD > **Status (verified 2026-11-07):** all five items below are fixed on `main` and covered by > regression tests (`OwlSpec`, `IRSpec`/`PythonSpec`, `Neo4jSpec`, `JavaSpec`/`PythonSpec`, `Neo4jSpec`/`GoSpec`). -> Status of later sections is tracked in `.planning/ROADMAP.md`. +> Status of later sections, checked 2026-11-15: fixed are 4.1, 4.3, 5.2, 5.3 (top-level +> symbols only), 7.1 and 7.3. Open: 4.4 (no `profile` option). Partial: 4.2 (only +> `def-relation` gives an OWL object property or edge), 5.1 (undeclared property ranges +> and axiom terms are not linted yet), 6.1 (`--java-package` exists; no Jackson +> annotations or builders), 6.2 (`@model_validator` done; `Field(...)` assignment +> remains), 6.3 (`elementId` done; edges use a generic `:RELATION` label), 7.2 (Gradle +> still generates under `src/generated/`). The checklists in this document are not +> ticked; treat this note and `CHANGELOG.md` as the record. ### 3.1 OWL Emitter Produces Malformed XML - **Location**: [`src/Emitters/Owl.hs:13-20`](../../src/Emitters/Owl.hs#L13-L20) diff --git a/docs/dev/TEST_COVERAGE.md b/docs/dev/TEST_COVERAGE.md index 21ef672..a62b2f1 100644 --- a/docs/dev/TEST_COVERAGE.md +++ b/docs/dev/TEST_COVERAGE.md @@ -1,7 +1,7 @@ # Test Suite & Coverage Report — OntoLogic -**Date:** 2026-10-18 -**Tooling used:** Haskell Program Coverage (HPC 0.6.1.0 via `stack test --coverage`), JUnit 5 (Gradle 8.5) +**Coverage last measured:** 2026-10-18 at 685 Hspec examples. It has not been re-measured since; the percentages below are that snapshot, not the 770-example suite at 8a6ae1a (v1.8.3). +**Tooling used:** Haskell Program Coverage (HPC 0.6.1.0 via `stack test --coverage`), JUnit 5 (Gradle 8.4) --- @@ -10,9 +10,9 @@ | Dimension | Value | |---|---| | Test framework(s) | Hspec 2.10+ (Haskell `ontologic-test`), JUnit 5 (Java `models-java`) | -| Total test files | 55 (54 Hspec specs in `test/`, 1 JUnit test in `models-java/`) | -| Total test cases | 689 (685 Hspec examples, 4 JUnit test cases) | -| CI-enforced? | Yes (`.github/workflows/ci.yml`, jobs `haskell-test` and `java-gradle-test`, and `scripts/check_coverage.sh`) | +| Total test files | 57 (56 Hspec spec files in `test/`, 1 JUnit test in `models-java/`), counted 2026-11-15 | +| Total test cases | 770 Hspec examples at 8a6ae1a (v1.8.3), plus 4 JUnit test cases; 685 Hspec examples at the 2026-10-18 coverage measurement | +| Enforced on GitHub? | No. The full gate (tests, `scripts/check_coverage.sh`, pending check) is run locally before every push. `.github/workflows/ci.yml` (jobs `haskell-test` and `java-gradle-test`) runs only when started by hand (`workflow_dispatch`). GitHub runs automatically only the docs link check and the Pages deployment. | | Runtime | ~32s wall-clock (`ontologic-test`), ~3s (`gradlew :models-java:test`) | --- @@ -78,34 +78,18 @@ --- -## 4. Coverage Gaps (Prioritized) +## 4. Remaining Coverage Gaps -### P0 — Untested code on the critical/security path +The earlier P0/P1/P2 gap tables were removed on 2026-11-15: every item in them was already listed as done in section 6 (`LSPSpec`, `Neo4jSpec`, `SqlSpec`, `SolverSpec`, `TPTPSpec`, `PythonSpec`, `JavaSpec`). Gaps that remain, from the 2026-10-18 measurement: -| Function / Module | File | Why it matters | +| Area | Measured | Gap | |---|---|---| -| `handleLSPRequest` (malformed JSON / unhandled methods) | `src/LSP.hs` | Language server is exposed to untrusted external editor clients; unhandled JSON-RPC parse exceptions can crash or hang the LSP stdio daemon. Verified in `test/LSPSpec.hs`. | -| `escapeTargetString` / sanitizer escaping edge cases | `src/Emitters/Neo4j.hs`, `src/Emitters/Sql.hs` | Neo4j Cypher and SQL query generation could be susceptible to injection or malformed syntax if identifiers contain unescaped quotes, backslashes, or control characters. Verified in `test/Neo4jSpec.hs` and `test/SqlSpec.hs`. | -| Subprocess crash / error diagnostics handling in `classifyOutput` | `src/Solver.hs` | Non-zero exit codes from external solvers (Z3, CVC5, Vampire) that print error banners or get killed by OS memory manager (OOM) must be captured and parsed reliably without crashing the reasoning pipeline. Verified in `test/SolverSpec.hs`. | - -### P1 — Untested core execution paths - -| Function / Module | File | Why it matters | -|---|---|---| -| `folToTPTP` (quantified / typed / arithmetic branches) | `src/Emitters/TPTP.hs` (80% expr) | TPTP emitter covers 80% of expressions; `TypedForAll`, `TypedExists`, comparison predicate branches (`lt`, `lte`, `gt`, `gte`), and custom property types (`PTCustom`) verified in `test/TPTPSpec.hs`. | -| `emitPythonExpr` / `emitFieldWithConstraints` | `src/Emitters/Python.hs` (74% expr) | Python Pydantic emitter covers 74% of expressions; compound conditional validators (`And`, `Or`, `Not`, `ne`), regex pattern constraints, and optional/list field wrappers verified in `test/PythonSpec.hs`. | -| `emitJava` (complex validation & array/set properties) | `src/Emitters/Java.hs` (72% expr) | Java model emitter covers 72% of expressions; tests for multi-dimensional range bounds, inverse comparison operators (`invertCompOp`), and non-numeric value bounds verified in `test/JavaSpec.hs`. | -| `runREPL.loop` / interactive commands | `src/REPL.hs` (52% expr) | The interactive REPL loop and several command branches (`:tree`, `:trace`, `:save`, error message rendering) are only tested via static evaluation rather than interactive streams. | -| `Tableau.formatTableauProof` / countermodel branches | `src/Prover/Tableau.hs` (68% expr) | Tableau refutation engine proof trace serialization and certain equality unification branches are not fully exercised by tests. | - -### P2 — Untested edge cases / error handling - -| Function / Module | File | Missing scenario | -|---|---|---| -| `extractModel` (Vampire definitions block) | `src/Solver.hs` | Parsing model valuations from Vampire when output starts with `% SZS output start Definitions and Model Updates.`. Verified in `test/SolverSpec.hs`. | -| `buildDerivationChain` / SAT conflict tracing | `src/Linter/SAT.hs` (75% expr) | Complex circular or multi-step contradiction chains formatting in `chainConflict` / `chainDerived`. | -| `resolveImportsWithSource` cycle handling | `src/Loader.hs` (77% expr) | Multi-hop circular import error chain diagnostics (`cycleChain`). | -| `defaultSolverOptions` resource exhaustion | `src/Solver.hs` | Explicit memory exhaustion (`-memory:<MB>`) triggering solver failure. | +| `REPL` | 56% expressions | Interactive loop and several command branches are only exercised through static evaluation | +| `LSP` | 65% expressions | Request handlers beyond malformed-input recovery | +| `Prover.Tableau` | 70% expressions | Proof formatting and equality unification branches | +| `IR.CNF`, `OntoLogic`, `Prover.*` | 31% to 45% top-level declarations | Mostly derived instances; see the measurement caveat in section 2 | +| Scripts | n/a | No fake-`PATH` testing of external binaries (section 5) | +| Docker Neo4j | n/a | Container teardown is untested | --- @@ -143,7 +127,7 @@ Evaluated for `scripts/regenerate_examples.sh`, `scripts/package_release.sh`, an ## 7. What's Already Solid -- **Semantic Parser (`src/Parser.hs`)**: **87% expressions, 100% top-level declarations, 0 boolean errors**. Thoroughly tested across 10 CLIF fixtures and all 54 spec suites. +- **Semantic Parser (`src/Parser.hs`)**: **87% expressions, 100% top-level declarations, 0 boolean errors**. Thoroughly tested across 10 CLIF fixtures and the Hspec suites. - **FOL Theory & Translation (`src/FOLTheory.hs`)**: **69% expressions, 74% declarations, 100% coverage on concept and relation translation**, with 0 unmapped axioms in the standard library. - **Automated SMT Solver Engine (`src/Solver.hs`)**: **73% expressions, 98% local declarations**, with multi-prover support (Z3, CVC5, Vampire, Native), SAT/UNSAT detection, unsatisfiable core extraction, and resource limits. - **Clausal Normal Form & Unification (`src/IR/Clausify.hs`, `src/Prover/Unification.hs`)**: **86% and 79% expression coverage**, testing Robinson MGU, occurs-check soundness, and clausal normal form translation. diff --git a/docs/dev/plans/2026-09-26-codebase-wide-review-and-remediation.md b/docs/dev/plans/2026-09-26-codebase-wide-review-and-remediation.md index bcbd6b7..1472bb7 100644 --- a/docs/dev/plans/2026-09-26-codebase-wide-review-and-remediation.md +++ b/docs/dev/plans/2026-09-26-codebase-wide-review-and-remediation.md @@ -1,4 +1,5 @@ # Codebase-Wide Architectural Review & Remediation Plan +Status: historical plan. See CHANGELOG.md for what shipped. - **Date**: 2026-09-26 - **Repository**: `bsommers/OntoLogic` diff --git a/docs/dev/plans/2026-09-26-fol-completeness-and-tech-debt-plan.md b/docs/dev/plans/2026-09-26-fol-completeness-and-tech-debt-plan.md index f865c1f..da6a3e1 100644 --- a/docs/dev/plans/2026-09-26-fol-completeness-and-tech-debt-plan.md +++ b/docs/dev/plans/2026-09-26-fol-completeness-and-tech-debt-plan.md @@ -1,7 +1,7 @@ # OntoLogic FOL Language Completeness Analysis & Technical Debt Remediation Plan - **Date**: 2026-09-26 -- **Status**: Draft / Roadmap Proposal +Status: Phases 1-4 SHIPPED in v1.4.0; later items are backlog. - **Author**: Antigravity (Advanced Agentic Coding Engine) - **Scope**: Formal logic semantics, compiler architecture, SMT translation, 16 target emitters, LSP/REPL, and test infrastructure. diff --git a/docs/dev/plans/2026-09-27-v1.5.0-tech-debt-remediation.md b/docs/dev/plans/2026-09-27-v1.5.0-tech-debt-remediation.md index 9bb4704..ee1ebe5 100644 --- a/docs/dev/plans/2026-09-27-v1.5.0-tech-debt-remediation.md +++ b/docs/dev/plans/2026-09-27-v1.5.0-tech-debt-remediation.md @@ -1,4 +1,5 @@ # v1.5.0 Tech Debt Remediation — Completed +Status: SHIPPED in v1.5.0. ## Summary of Changes 1. **DPLL dead code fix**: `Linter.SAT.checkOntologySAT` now surfaces non-Horn UNSAT via DPLL fallback with clause origins diff --git a/docs/dev/plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md b/docs/dev/plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md index 024fdac..9070a78 100644 --- a/docs/dev/plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md +++ b/docs/dev/plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md @@ -1,4 +1,5 @@ # OntoLogic v1.5.0 — Tech Debt Remediation Implementation Plan +Status: SHIPPED in v1.5.0. > **Target**: Gemini Flash 3.8 (high) autonomous execution > **Baseline**: v1.4.0, commit `b084531`, 410 tests passing diff --git a/docs/dev/superpowers/REPLAY_PLAYBOOK.md b/docs/dev/superpowers/REPLAY_PLAYBOOK.md index ecec234..1794cc6 100644 --- a/docs/dev/superpowers/REPLAY_PLAYBOOK.md +++ b/docs/dev/superpowers/REPLAY_PLAYBOOK.md @@ -326,7 +326,7 @@ OntoLogic/ │ ├── OwlSpec.hs # OWL XML structure tests │ ├── MermaidSpec.hs # Mermaid diagram tests │ ├── D2Spec.hs # D2 diagram tests -│ ├── ExamplesSpec.hs # Integration tests running all 12 example models against all targets +│ ├── ExamplesSpec.hs # Integration tests running all 30 example models against all targets │ └── MainSpec.hs # CLI argument & driver tests ├── examples/ # Real-world domain models (.logic) ├── models-java/ # Java Gradle subproject with Bean Validation & JUnit tests @@ -337,3 +337,5 @@ OntoLogic/ │ └── plans/ # Master plan documents └── gradlew # Pinned Gradle 8.4 wrapper ``` + +The tree above lists only a selection: `test/` now holds 60 `*Spec.hs` files and `examples/` holds 30 `.logic` models. diff --git a/docs/dev/superpowers/plans/2026-07-18-implement-ontologic-recommendations.md b/docs/dev/superpowers/plans/2026-07-18-implement-ontologic-recommendations.md index d0e7a44..bd4b3d3 100644 --- a/docs/dev/superpowers/plans/2026-07-18-implement-ontologic-recommendations.md +++ b/docs/dev/superpowers/plans/2026-07-18-implement-ontologic-recommendations.md @@ -1,4 +1,5 @@ # Implement OntoLogic Recommendations Implementation Plan +Status: historical plan. See CHANGELOG.md for what shipped. > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/dev/superpowers/plans/2026-09-05-ontologic-core-improvements.md b/docs/dev/superpowers/plans/2026-09-05-ontologic-core-improvements.md index 6ee841b..59fb6e8 100644 --- a/docs/dev/superpowers/plans/2026-09-05-ontologic-core-improvements.md +++ b/docs/dev/superpowers/plans/2026-09-05-ontologic-core-improvements.md @@ -1,4 +1,5 @@ # OntoLogic Core Improvements Implementation Plan +Status: historical plan. See CHANGELOG.md for what shipped. > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/dev/superpowers/plans/2026-09-05-robust-test-suite.md b/docs/dev/superpowers/plans/2026-09-05-robust-test-suite.md index 558e139..cbc0f61 100644 --- a/docs/dev/superpowers/plans/2026-09-05-robust-test-suite.md +++ b/docs/dev/superpowers/plans/2026-09-05-robust-test-suite.md @@ -1,4 +1,5 @@ # Robust Testing Suite Implementation Plan +Status: historical plan. See CHANGELOG.md for what shipped. > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/dev/superpowers/plans/2026-09-07-security-and-hardening-fixes.md b/docs/dev/superpowers/plans/2026-09-07-security-and-hardening-fixes.md index ce79210..fe6ce86 100644 --- a/docs/dev/superpowers/plans/2026-09-07-security-and-hardening-fixes.md +++ b/docs/dev/superpowers/plans/2026-09-07-security-and-hardening-fixes.md @@ -1,4 +1,5 @@ # OntoLogic Security, Hardening & Hygiene Implementation Plan +Status: historical plan. See CHANGELOG.md for what shipped. > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/dev/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md b/docs/dev/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md index 6f12994..d31ea90 100644 --- a/docs/dev/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md +++ b/docs/dev/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md @@ -1,4 +1,5 @@ # Milestone 5 Plan: Multi-Entity Relational Axioms & Graph Transpilation +Status: historical plan. See CHANGELOG.md for what shipped. > **Context:** Expands OntoLogic's compiler and intermediate representation to support cross-entity relationships (`(def-relation ...)` and multi-variable First-Order Logic predicates), transpiling them into Neo4j graph relationships, OWL Object Properties, OOP association references, and visualizer relationship arrows. > **Tracking Document:** [`docs/dev/superpowers/REPLAY_PLAYBOOK.md`](../REPLAY_PLAYBOOK.md) diff --git a/docs/dev/superpowers/plans/2026-09-13-type-system-and-model-ir.md b/docs/dev/superpowers/plans/2026-09-13-type-system-and-model-ir.md index af2d2cb..47aa05a 100644 --- a/docs/dev/superpowers/plans/2026-09-13-type-system-and-model-ir.md +++ b/docs/dev/superpowers/plans/2026-09-13-type-system-and-model-ir.md @@ -1,4 +1,5 @@ # Milestone 4 Plan: Type System Refactoring & Compiler Intermediate Representation (IR) +Status: historical plan. See CHANGELOG.md for what shipped. > **Context:** Evolution from an ad-hoc pattern-matching emitter pipeline to a strongly typed compiler architecture with an Intermediate Representation (IR), premise-aware axiom extraction, and property-based verification. > **Tracking Document:** [`docs/dev/superpowers/REPLAY_PLAYBOOK.md`](../REPLAY_PLAYBOOK.md) diff --git a/docs/dev/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md b/docs/dev/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md index cc1bcc5..b0d3458 100644 --- a/docs/dev/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md +++ b/docs/dev/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md @@ -1,4 +1,5 @@ # OntoLogic Future Roadmap & Architectural Plan: 3-Tier Cyber, AI Governance, Threat Modeling & GRC Ontologies +Status: historical plan. See CHANGELOG.md for what shipped. > **Document ID:** `docs/dev/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md` > **Methodology:** OpenGSD (Get Stuff Done) Phased Architecture & Execution diff --git a/docs/dev/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md b/docs/dev/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md index 2e5ed6b..12a3bae 100644 --- a/docs/dev/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md +++ b/docs/dev/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md @@ -1,4 +1,5 @@ # Future Capabilities & Target Emitters Master Plan +Status: historical plan. See CHANGELOG.md for what shipped. **Document:** `docs/dev/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md` **Date:** 2026-09-14 diff --git a/docs/dev/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md b/docs/dev/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md index 2687781..e426e8d 100644 --- a/docs/dev/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md +++ b/docs/dev/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md @@ -1,4 +1,5 @@ # Milestone 6 Plan: Modular Namespacing & Multi-File Imports +Status: historical plan. See CHANGELOG.md for what shipped. > **Context:** Expands OntoLogic's DSL, parser, linter, and IR to support modular multi-file ontologies (`(import "path/to/file.logic")` and `(namespace "prefix")`), enabling the decomposition of large enterprise ontologies (BFO, CCO, MITRE, NIST AI RMF) into reusable components. > **Tracking Document:** [`docs/dev/superpowers/REPLAY_PLAYBOOK.md`](../REPLAY_PLAYBOOK.md) diff --git a/docs/dev/superpowers/plans/2026-09-19-review-remediation.md b/docs/dev/superpowers/plans/2026-09-19-review-remediation.md index 341822b..4f8a52b 100644 --- a/docs/dev/superpowers/plans/2026-09-19-review-remediation.md +++ b/docs/dev/superpowers/plans/2026-09-19-review-remediation.md @@ -1,4 +1,5 @@ # Review Remediation Implementation Plan +Status: SHIPPED. All issues in this plan were fixed; the unticked boxes below are historical. > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. @@ -542,7 +543,7 @@ The VS Code side of #16 (success only on an explicit result) is done in Task 0.2 **Files:** - Modify: `src/Solver.hs` (new export) - Modify: `src/Main.hs` (`runSolverCheck`, as rewritten in Task 0.3) -- Modify: `HOW_TO_USE.md` (the `solve` section around line 221) +- Modify: `docs/using.md` (the `solve` section around line 221) - Test: `test/SolverSpec.hs` **Interfaces:** @@ -597,7 +598,7 @@ Import `exitWith` from `System.Exit` and `solverExitCode` from `Solver`. - [ ] **Step 4: Document the codes** -In `HOW_TO_USE.md`, after the `--solve -p cvc5` example (line 225), add: +In `docs/using.md`, after the `--solve -p cvc5` example (line 225), add: ```markdown `--solve` exit codes: `0` = satisfiable (consistent), `1` = unsatisfiable or solver error, `2` = the solver answered `unknown`. @@ -609,7 +610,7 @@ Run: `stack test --ghc-options="-Wall -Werror"` Expected: all pass. ```bash -git add src/Solver.hs src/Main.hs HOW_TO_USE.md test/SolverSpec.hs +git add src/Solver.hs src/Main.hs docs/using.md test/SolverSpec.hs git commit -m "fix(cli): exit 2 when the solver answers unknown (#31)" ``` @@ -695,7 +696,7 @@ The steps below assume option 1. **Files:** - Modify: `docs/capabilities.json`, `docs/CAPABILITIES.md` - Create: `ontology/README.md`, `ontologic-lib/factory_domain.logic` (vendored) -- Modify: `.ontology/README.md`, `HOW_TO_USE.md` +- Modify: `.ontology/README.md`, `docs/using.md` - Test: `test/MainSpec.hs`, `test/StandardLibrarySpec.hs` - [ ] **Step 1: Write the failing tests** @@ -787,7 +788,7 @@ Append to `.ontology/README.md`: `ontology/` holds the component ontology written by the ecosystem spider. Different owners, so both are kept. ``` -Add a line to `HOW_TO_USE.md` pointing at both READMEs. +Add a line to `docs/using.md` pointing at both READMEs. - [ ] **Step 5: Run the tests and commit** @@ -795,7 +796,7 @@ Run: `stack test --ghc-options="-Wall -Werror"` Expected: all pass. ```bash -git add docs/capabilities.json docs/CAPABILITIES.md ontology/README.md .ontology/README.md ontologic-lib/factory_domain.logic HOW_TO_USE.md test/MainSpec.hs test/StandardLibrarySpec.hs +git add docs/capabilities.json docs/CAPABILITIES.md ontology/README.md .ontology/README.md ontologic-lib/factory_domain.logic docs/using.md test/MainSpec.hs test/StandardLibrarySpec.hs git commit -m "fix(capabilities): real entrypoints and test command; vendor factory_domain; document ontology dirs (#30)" ``` @@ -1440,7 +1441,7 @@ git add package.yaml ontologic.cabal src/Loader.hs src/Main.hs test/ImportSpec.h git commit -m "fix(loader): find the standard library from any directory; add --lib-path (#29)" ``` -Also add a sentence about `ONTOLOGIC_PATH` and `--lib-path` to the stdlib section of `HOW_TO_USE.md`. +Also add a sentence about `ONTOLOGIC_PATH` and `--lib-path` to the stdlib section of `docs/using.md`. **Wave 1 gate:** all Wave 1 PRs merged, CI green on `main`, milestone `Wave 1: Foundations` shows 0 open issues. @@ -2049,7 +2050,7 @@ Asserting non-emptiness inside the consistency check would have made both questi **Files:** - Modify: `src/Solver.hs` (`proveSubsumptionWith`, `findUnsatConceptsWith`, `emitSMTForConsistency`; delete `checkSingleClassSatisfiability`; new export `untranslatedAxioms`) - Modify: `src/Main.hs` (`runSolverCheck`), `src/REPL.hs` (`:solve` branch) -- Modify: `HOW_TO_USE.md` (solver section) +- Modify: `docs/using.md` (solver section) - Test: `test/SolverSpec.hs`, `test/MainSpec.hs` **Interfaces:** @@ -2209,7 +2210,7 @@ Apply the same warning block to the REPL `:solve` output, prepended to the retur - [ ] **Step 5: Document** -In `HOW_TO_USE.md`'s solver section, add: "`--solve` reports two things. **Consistency**: whether the axioms can be satisfied at all. **Coherence**: which concepts can have no instance, given the axioms, bounds and hierarchy (the same check as the REPL's `:unsat`). It exits non-zero if either fails, `2` if the solver could not decide. Axioms the SMT encoding cannot express are listed first." +In `docs/using.md`'s solver section, add: "`--solve` reports two things. **Consistency**: whether the axioms can be satisfied at all. **Coherence**: which concepts can have no instance, given the axioms, bounds and hierarchy (the same check as the REPL's `:unsat`). It exits non-zero if either fails, `2` if the solver could not decide. Axioms the SMT encoding cannot express are listed first." - [ ] **Step 6: Run the tests and commit** @@ -2217,7 +2218,7 @@ Run: `stack test --ghc-options="-Wall -Werror"` Expected: all pass, including the older solver tests (Car ⊑ Vehicle, the CVC5 cases, and `ContradictoryNode`). If the bfo_2020 timing test is close to 60 s, record the measured time in the PR. ```bash -git add src/Solver.hs src/Main.hs src/REPL.hs HOW_TO_USE.md test/SolverSpec.hs test/MainSpec.hs +git add src/Solver.hs src/Main.hs src/REPL.hs docs/using.md test/SolverSpec.hs test/MainSpec.hs git commit -m "fix(solver): send FOL axioms to the solver; one-process :unsat; report untranslated axioms (#18)" ``` diff --git a/docs/dev/superpowers/plans/2026-10-01-canonical-cnf-and-native-prover.md b/docs/dev/superpowers/plans/2026-10-01-canonical-cnf-and-native-prover.md index 0e8bf33..a30d9a4 100644 --- a/docs/dev/superpowers/plans/2026-10-01-canonical-cnf-and-native-prover.md +++ b/docs/dev/superpowers/plans/2026-10-01-canonical-cnf-and-native-prover.md @@ -1,7 +1,8 @@ # Milestone v1.7.0 Plan: Canonical Clausal Normal Form (CNF) IR & Native First-Order Prover Engine +Status: SHIPPED in v1.7.0. > **Context:** Evolution from relying exclusively on external automated theorem provers (Z3, CVC5, Vampire) over process stdio to providing a native, zero-dependency First-Order Logic (FOL) reasoning engine. Incorporates a formal Canonical Clausal Normal Form (CNF) intermediate representation and a built-in resolution/tableau prover directly in Haskell. -> **Tracking Document:** [`.planning/ROADMAP.md`](../../../../.planning/ROADMAP.md) +> **Tracking Document:** the project roadmap --- diff --git a/docs/dev/superpowers/plans/2026-10-01-clif-interop-fol-port.md b/docs/dev/superpowers/plans/2026-10-01-clif-interop-fol-port.md index e7ebf7d..8daa095 100644 --- a/docs/dev/superpowers/plans/2026-10-01-clif-interop-fol-port.md +++ b/docs/dev/superpowers/plans/2026-10-01-clif-interop-fol-port.md @@ -1,7 +1,8 @@ # Milestone v1.8.0 Plan: CLIF Interop: Port `feature/upstream-extensions` onto `main` +Status: SHIPPED in v1.8.0. > **Context:** [clif2OntoLogic](https://github.com/bsommers/clif2OntoLogic) translates COLORE / BFO-2020 Common Logic (CLIF) ontologies into `.logic` modules. Its Phase 08 work ("UP-01..UP-05") went onto branch `feature/upstream-extensions` (`b4376cf`), which forked from `064530a` (2026-09-17) and was **never merged**. Since then `main` has independently added equality (`Eq`), function terms (`Apply`), typed quantifiers, `Top`/`Bottom`, and a FOL→SMT theory (`FOLTheory.hs`). This milestone moves the parts of the branch that are still missing onto `main`, **without changing the `FOL` / `Term` data types**. Once it ships, clif2OntoLogic re-pins to the v1.8.0 tag. -> **Tracking Document:** [`.planning/ROADMAP.md`](../../../.planning/ROADMAP.md) +> **Tracking Document:** the project roadmap > **Sequencing:** Start after v1.7.0 (CNF + native prover) has merged. Branch: `feature/clif-interop-v1.8.0` off `main`. > **Status:** Plan only. No code has been written. diff --git a/docs/dev/superpowers/plans/2026-10-03-string-constants-in-fol-backends.md b/docs/dev/superpowers/plans/2026-10-03-string-constants-in-fol-backends.md index 8d0c771..3f97b72 100644 --- a/docs/dev/superpowers/plans/2026-10-03-string-constants-in-fol-backends.md +++ b/docs/dev/superpowers/plans/2026-10-03-string-constants-in-fol-backends.md @@ -1,6 +1,6 @@ # String constants in the FOL backends -**Status:** proposal from clif2OntoLogic (2026-10-03). Not scheduled. Additive to +Status: historical plan. See CHANGELOG.md for what shipped. `2026-10-01-clif-interop-fol-port.md`; does not touch the v1.7.0 work. ## Problem @@ -54,5 +54,5 @@ literal as an argument of an entity predicate is ill-sorted. ## Affected clif2OntoLogic inputs Five COLORE files carry CLIF strings that reach `--solve`; see -clif2OntoLogic `.planning/phases/16-reverse-transpiler-round-trip-semantic-fidelity/16-05-PLAN.md` +clif2OntoLogic plan 16-05 (reverse-transpiler round-trip semantic fidelity) ("Known upstream limitation"). diff --git a/docs/dev/superpowers/plans/2026-10-14-def-relation-smt-facts.md b/docs/dev/superpowers/plans/2026-10-14-def-relation-smt-facts.md index 1b2457e..38f92c7 100644 --- a/docs/dev/superpowers/plans/2026-10-14-def-relation-smt-facts.md +++ b/docs/dev/superpowers/plans/2026-10-14-def-relation-smt-facts.md @@ -1,6 +1,6 @@ # `def-relation` as an asserted fact in the SMT backend -**Status:** proposal from clif2OntoLogic (2026-10-14). Not scheduled. Additive; touches only +Status: SHIPPED in v1.8.1. `src/Emitters/SMT.hs` (`emitRelations`) if adopted. ## Problem diff --git a/docs/purpose.md b/docs/purpose.md index 187ddd7..e92b413 100644 --- a/docs/purpose.md +++ b/docs/purpose.md @@ -100,7 +100,11 @@ and records about them (information content entities). That keeps a socket, a cable and a social tie from collapsing into one `Connection`, lets mining, cloud and manufacturing models merge without collisions, and gives you a principled check against nonsense such as "the software weighs 5 kg" (software is a -generically dependent continuant; only material entities have mass). +generically dependent continuant; only material entities have mass). Be aware +of the current limit: the bundled `bfo_2020.logic` declares the BFO categories +and relations but has almost no axioms yet, so it does not by itself reject such +statements; you add the axioms that say so. Making the shipped BFO file carry +them is planned for v2.0.0. **First-order logic as the language of definition.** Triples cannot express "all pumps have a safety valve" or "if a mining process runs, some excavator @@ -120,9 +124,10 @@ deterministic for the same input, and Megaparsec gives a precise, testable parser for untrusted `.logic` files. The trade is explicit: setup cost is higher than a loose graph, maintenance cost -is much lower, and ambiguity is removed once, at the foundation. Alerts become -explainable ("violated axiom 4: active oven must have temperature above 100") -instead of a bare score. +is much lower, and ambiguity is removed once, at the foundation. The aim is +that alerts become explainable ("violated axiom 4: active oven must have +temperature above 100") instead of a bare score; today `--explain-unsat` does +that for contradictions in the ontology itself, not for data. ## Where it pays off @@ -131,9 +136,11 @@ instead of a bare score. - **Security, threat intelligence and compliance.** The standard library covers STIX, ATT&CK, D3FEND, NIST and AI-governance frameworks; compliance rules are axioms you can check. See the [standard library](standard-library.md). -- **Grounding AI agents.** An agent's proposed actions can be checked against - domain invariants before they run, so a violation is rejected - deterministically. +- **Grounding AI agents.** The aim is that an agent's proposed actions can be + checked against domain invariants before they run. That is not built yet: + OntoLogic has no instance-data or runtime-check feature today. What works now + is proving the invariants consistent and generating validators for them; wiring + those validators into an agent is up to you. - **Software and systems engineering.** Architecture, delivery and requirements models stay consistent with the code generated from them. See the [domain gallery](domains/README.md). diff --git a/docs/standard-library.md b/docs/standard-library.md index 5d85fbd..d92e9c4 100644 --- a/docs/standard-library.md +++ b/docs/standard-library.md @@ -1,6 +1,6 @@ # Standard Library -`ontologic-lib/` ships 19 ready-made `.logic` modules, layered on a common +`ontologic-lib/` ships 18 ready-made `.logic` modules, layered on a common upper ontology. Import what you need by bare file name; the transitive imports come with it. @@ -44,7 +44,7 @@ Arrows point from an imported module to the module that imports it. ## Importing ```lisp -(namespace "cco" "http://www.ontologyrepository.com/CommonCoreOntologies/") +(namespace cco "http://www.ontologyrepository.com/CommonCoreOntologies/") (import "cco_core.logic") ; also pulls in bfo_2020.logic (import "mitre_attack.logic") ; also pulls in stix_cve, uco_observables, cco_core, bfo_2020 @@ -60,9 +60,10 @@ ontologic -i my_model.logic --solve ontologic -i my_model.logic -t sql -o out/ ``` -Imports are searched in the importing file's directory, `$ONTOLOGIC_PATH`, the -directory beside the binary, the package data directory, `./ontologic-lib`, and -the current directory last. Add folders with `--lib-path DIR`. A module imported +Imports are searched in the importing file's directory, then each `--lib-path DIR` +(repeatable), `$ONTOLOGIC_PATH`, the directory beside the binary, the package data +directory, `./ontologic-lib`, and the current directory last. An import must name +a `.logic` file. A module imported by two paths is loaded once. See [architecture](architecture.md#frontend-and-loader). ## Upper ontologies @@ -106,12 +107,16 @@ by two paths is loaded once. See [architecture](architecture.md#frontend-and-loa Concept counts for `ecosystem_unified.logic` are its own additions; the imports bring the rest. +## Finding the names a library defines + +Library concepts carry their namespace prefix, so you write `bfo:MaterialEntity`, not `MaterialEntity`. To list what a module offers, open the file (the `def-concept` lines are the names), or load it in the REPL with `:load ontologic-lib/cco_core.logic` and type `:show`. The linter reports `Undeclared parent concept` when a name or prefix is wrong. + ## Instance data `ontologic-lib/ecosystem.logic` is tested against a small synthetic Turtle sample, [`test/fixtures/ecosystem_symbols.ttl`](../test/fixtures/ecosystem_symbols.ttl). Individuals can also be declared directly with `def-individual` (see the -[language reference](user-guide/language-reference.md)). +[language reference](user-guide/language-reference.md)). Today `def-individual` only feeds the solver; no generated target (OWL, Neo4j, SQL, TypeScript and so on) emits individuals, and OntoLogic has no way yet to check a data file against the model. ## Domain examples diff --git a/docs/user-guide/README.md b/docs/user-guide/README.md index 2634e94..013b9f4 100644 --- a/docs/user-guide/README.md +++ b/docs/user-guide/README.md @@ -35,7 +35,7 @@ New to OntoLogic: read 1 to 3 in order, then pick topics as needed. SAT / UNSAT / unknown code, schemas, diagrams ``` -The linter always runs first. If it finds an error, nothing else runs (no solving, no emission) and the exit code is 1. +The linter always runs first. If it finds an error, nothing else runs (no solving, no emission) and the exit code is 1. Warnings are printed and the run continues. ## Related documents diff --git a/docs/user-guide/axioms-and-reasoning.md b/docs/user-guide/axioms-and-reasoning.md index 01ef690..9dce9dd 100644 --- a/docs/user-guide/axioms-and-reasoning.md +++ b/docs/user-guide/axioms-and-reasoning.md @@ -14,7 +14,7 @@ Axioms are full first-order logic, not Horn clauses (see [Language reference](la | Subsumption | `(forall (x) (implies (Hybrid x) (Truck x)))` (also implied by `(def-concept Hybrid Truck)`) | | Rule | `(forall (o) (implies (and (Oven o) (eq is_active True)) (gt temperature 100)))` | -Cardinality (`:cardinality`), `:optional`, and `:default` on properties and relations shape generated code and schemas but are not part of the solver's logical theory. If you need a cardinality to take part in reasoning, state it as an axiom. +Cardinality (`:cardinality`), `:optional`, and `:default` on properties and relations shape generated code and schemas but are not part of the solver's logical theory. Disjointness and existential axioms are checked by the solver but are not enforced by generated code and are not exported to OWL (there is no `owl:disjointWith` in the output). If you need a cardinality to take part in reasoning, state it as an axiom. Disjointness is not a separate keyword; write it as an implication to a negation, as above. The linter recognizes that pattern. @@ -22,11 +22,11 @@ Disjointness is not a separate keyword; write it as an implication to a negation `-t lint` (or any run, since the linter always goes first) checks: -- Undeclared parents, property domains, and relation endpoints; duplicate concepts, properties, relations, and namespace prefixes. +- Undeclared parents, property domains and ranges, property types (a type such as `Int` or `DateTime` that is neither built in nor a declared concept), and relation endpoints; duplicate concepts, properties and relations; and a namespace prefix declared with two different URIs (repeating the same prefix and URI is fine). - Circular inheritance. - Direct contradictions inside one axiom (`P and not P`, asserted `bottom`). - Impossible numeric ranges on one property (`gt 5` with `lt 3`), within one axiom and across axioms for a concept and its ancestors. -- A propositional/Horn pass over the hierarchy and disjointness axioms that finds concepts forced to be empty, for example a subclass of two disjoint concepts. +- A propositional/Horn pass over the hierarchy and disjointness axioms that finds concepts forced to be empty, for example a subclass of two disjoint concepts. These findings are **warnings** (`warning:`, exit code 0), because the solver is the real judge of consistency. An axiom that mentions a predicate or property name you never declared also gets a warning. ```bash ontologic-exe -i test/fixtures/domains/domain_mining_conflict.logic -t lint @@ -38,7 +38,7 @@ examples/domain_mining.logic:27:14: error: Cross-axiom contradiction on GasSenso examples/domain_mining.logic:27:14: error: Cross-axiom contradiction on GasSensor.methane_level: lt 3 and gt 5 ``` -(Paths are printed in full in real output; they are shortened here.) Any lint error stops the run with exit code 1. Because the linter runs first, `--solve` on an ontology with lint errors prints those errors and does not reach the solver. +(Paths are printed in full in real output; they are shortened here.) Any lint error (not a warning) stops the run with exit code 1. Every error line carries `file:line:col`, except `Axiom contradiction: bottom (false) asserted.`, which has no position. Because the linter runs first, `--solve` on an ontology with lint errors prints those errors and does not reach the solver. Add `--warn-unmapped` to also report axioms that the field-constraint emitters cannot express (see below). @@ -52,7 +52,7 @@ How the translation works (`src/FOLTheory.hs`): |--------|-----------------| | concept `C` | predicate `is_C(x)` | | `(def-concept C P)` | `is_C(x) => is_P(x)` | -| relation `r` | predicate `rel_r(x, y)`, with domain and range implications | +| relation `r` | predicate `rel_r(x, y)`. The declared domain and range are **not** asserted as axioms on the Z3 and CVC5 route today, so `r(a, b)` does not by itself make `a` a domain instance. If you need that, state it as an axiom. Planned for v1.9.0 | | data property `p : T` | function `prop_p(x) -> T` (`Int`, `Real`, `Bool`, `String`) | | entity-valued property | treated as a relation | | comparison `(gt p v)` in a quantifier | `prop_p(<innermost bound variable>) > v` | @@ -64,15 +64,17 @@ How the translation works (`src/FOLTheory.hs`): ### Axioms that are not sent -Some axioms cannot be translated. They are listed before the verdict, and the verdict says how many were checked: +Some axioms cannot be translated. A check that leaves any axiom out is a partial check, and a partial check can never report "consistent": the axiom that was dropped may be the one that contradicts the rest. If the axioms that were sent are satisfiable, the verdict is **unknown** (exit 2). The message comes first, followed by the list of axioms that were not sent: ```text +⚠️ SMT Solver Result (unknown): The axioms that were checked are consistent, but 1 axiom(s) could not be checked, so consistency of the whole ontology is unknown. ⚠️ 1 axiom(s) were not sent to the solver: - ForAll "c" (Implies (And (Predicate "Controller" [Var "c"]) (Eq (Var "safety_status") (Constant "False"))) (Eq (Var "active") (Constant "False"))) (unbound variable active) -✅ SMT Satisfiable (SAT) — Ontology is logically consistent for the 1 axioms checked. ``` -Common reasons: an unbound variable, a comparison outside any quantifier, an ordering comparison on a non-numeric property, a property used with conflicting types, a predicate used with different arities. A SAT verdict only covers the axioms actually sent. Fix the axiom or use `--free-constants`. +UNSAT stands: if the axioms that were sent already contradict each other, the whole ontology is contradictory. The same rule applies in the REPL (`:solve`, `:model`, `:explain`; a `:prove` that would say "Disproved" says unknown, while "Proved" stands) and in the language server's `ontologic.solve` command. + +Common reasons: an unbound variable, a comparison outside any quantifier, an ordering comparison on a non-numeric property, a property used with conflicting types, a predicate used with different arities. Fix the axiom (declare the missing name or correct the arity) or use `--free-constants`. ### `--free-constants` @@ -84,9 +86,9 @@ ontologic-exe -i free.logic --solve --free-constants ``` ```text +⚠️ SMT Solver Result (unknown): The axioms that were checked are consistent, but 1 axiom(s) could not be checked, so consistency of the whole ontology is unknown. ⚠️ 1 axiom(s) were not sent to the solver: - - ForAll "x" (Implies (Predicate "A" [Var "x"]) (Predicate "Open" [Var "y"])) (unbound variable in predicate Open) -✅ SMT Satisfiable (SAT) — Ontology is logically consistent for the 0 axioms checked. + - ForAll "x" (Implies (Predicate "A" [Var "x"]) (Predicate "Open" [Var "y"])) (unsupported predicate Open/1) ... ℹ️ Free constants mode enabled (--free-constants): undeclared free variables are treated as Entity constants. ✅ SMT Satisfiable (SAT) — Ontology is logically consistent. @@ -99,12 +101,14 @@ ontologic-exe -i free.logic --solve --free-constants | `✅ SMT Satisfiable (SAT)` and `✅ All concepts are satisfiable` | Consistent and coherent | 0 | | `❌ SMT Unsatisfiable (UNSAT)` | The axioms contradict each other | 1 | | `❌ Unsatisfiable / empty concept(s): A B` | Those concepts cannot have instances | 1 | -| `⚠️ SMT Solver Result (unknown): ...` | Timeout, limit, or solver gave up; not a proof either way | 2 | -| `❌ SMT Solver Error: ...` | The solver ran and failed | 1 | +| `⚠️ SMT Solver Result (unknown): ...` | Timeout, limit, or solver gave up; or the checked axioms are satisfiable but some axioms were not sent (see above). Not a proof either way | 2 | +| `❌ SMT Solver Error: ...` | The solver ran and failed, printed an error message, could not parse the input, or gave no single clear verdict | 1 | | `⚠️ Concept coherence check could not run` | Coherence step failed | 2 | When several checks run, the worst code wins: 1 beats 2 beats 0. +The solver bridge fails closed. A Z3 `(error ...)` line, a Vampire parse failure, or output without exactly one verdict is a solver error (exit 1), never SAT. A Vampire `GaveUp` or `ResourceOut` result is reported as unknown. The word `unsat` is never read as `sat`. For the TPTP route OntoLogic calls Vampire with `--input_syntax tptp`. + ### `--explain-unsat` When the verdict is UNSAT, `--explain-unsat` re-runs the problem with every axiom named and prints the unsatisfiable core, the subset of axioms that already contradict each other: @@ -154,7 +158,7 @@ A model is one possible world, usually a tiny one. Concepts that are empty in th | `z3` | External. Handles integer and real bounds well; supports `-T` and `--solve-memory`. Good default | | `cvc5` | External. Run with finite-model finding and unsat-core support; supports `-T` | | `vampire` | External. First-order specialist; given SMT-LIB or TPTP input; supports `-T` | -| `native` | Built into the binary (tableau and resolution). No install needed; honours `-T`; reports unknown on step or clause limits | +| `native` | Built into the binary (tableau and resolution). No install needed; honours `-T`; reports unknown on step or clause limits, and always answers unknown (exit 2) when the theory uses equality, because it does not reason about equality | | `auto` | Tries `z3`, `cvc5`, `vampire` in order, skipping any that is not installed; if none is installed, falls back to `native`. A solver that is installed but fails is reported, not skipped | Practical guidance: use `z3` or `cvc5` for ontologies with numeric property bounds. `native` and `vampire` have no arithmetic. OntoLogic gives them one background axiom for each pair of numeric bounds in the file that no number can meet together (such as `gte 100` and `lt 50`), so they catch contradictions like the balance example above. They still miss contradictions that need real arithmetic, such as integer gaps (`gt 5` and `lt 6` on an `Integer`) or bounds derived from sums. When one of them gives an all-clear on an ontology that uses `gt`, `gte`, `lt` or `lte`, OntoLogic prints a warning that the answer was reached without arithmetic and should be confirmed with `z3` or `cvc5`. The domain fixtures in `test/fixtures/domains/` are checked with Z3 (then CVC5) for this reason. For purely taxonomic and relational reasoning, all backends agree. If two provers disagree, trust UNSAT from an SMT solver and treat the other's SAT as incomplete. @@ -167,7 +171,7 @@ ontologic-exe -i big.logic --solve -p z3 -T 60 --solve-memory 2048 | Flag | Applies to | Behaviour | |------|-----------|-----------| -| `-T/--solve-timeout SECONDS` | z3, cvc5, vampire, native | Positive integer. Each backend gets its own limit flag; external solvers are also killed after the limit plus a 2 second grace period. A timeout is reported as unknown (exit 2), never as an error | +| `-T/--solve-timeout SECONDS` | z3, cvc5, vampire, native | Positive integer. If you do not give `-T`, the limit is 60 seconds (CLI, REPL and language server). Very large values are clamped rather than overflowing. Each backend gets its own limit flag; external solvers are also killed after the limit plus a 2 second grace period. A timeout is reported as unknown (exit 2), never as an error | | `--solve-memory MB` | z3 only | Positive integer. With `-p cvc5|vampire|native` it prints `⚠️ --solve-memory is not supported by CVC5 and is ignored.`; with `auto` it warns it applies only if Z3 is the selected prover | Zero and negative values are rejected: `option -T: expected a positive integer, got '0'`. For Z3 and CVC5 the coherence check runs all concepts in one solver process, so `-T` is a single budget for that whole batch; Vampire and native get the budget once per concept. @@ -192,9 +196,9 @@ ontologic-exe -i fleet.logic --cnf ~Car(X1) | ~Truck(X1) ~Car(X1) | Vehicle(X1) ~Truck(X1) | Vehicle(X1) -~Truck(X1) | gte(X2, 0) -~Vehicle(X1) | gte(X2, 0) -~Vehicle(X1) | lte(X2, 130) +~Truck(X1) | gte(prop_max_load(X1), 0) +~Vehicle(X1) | gte(prop_speed(X1), 0) +~Vehicle(X1) | lte(prop_speed(X1), 130) ~drives(X1, X2) | Driver(X1) ~drives(X1, X2) | Vehicle(X2) ``` diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index 18462e1..5c7b21c 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -8,7 +8,8 @@ ontologic-exe [-i|--input FILE] [-t|--target TARGET] [-o|--output PATH] [--neo4j-edition EDITION] [--render] [--repl] [--cnf] [--lsp] [--solve] [--warn-unmapped] [--explain-unsat] [--inspect-model] [--free-constants] [-T|--solve-timeout SECONDS] - [--solve-memory MB] [--lib-path DIR] + [--solve-memory MB] [--lib-path DIR] [--allow-absolute-imports] + [--version] ``` ## Flags @@ -22,7 +23,7 @@ ontologic-exe [-i|--input FILE] [-t|--target TARGET] [-o|--output PATH] | `--java-package` | PKG | Package for the `java` target. Default `ontologic.generated` | | `--base-iri` | IRI | Base IRI for `owl` and `shacl`. Default: the ontology's first namespace IRI (trailing `#` or `/` stripped), else `http://example.org/ontologic` | | `-p`, `--prover` | z3, cvc5, vampire, native, auto | Solver backend for `--solve`. Default `auto` | -| `--neo4j-edition` | community, enterprise | Edition for `neo4j` constraints. Default `enterprise`; with `community`, node-property-existence constraints are written commented out | +| `--neo4j-edition` | community, enterprise | Any other value is rejected with an error. Edition for `neo4j` constraints. Default `enterprise`; with `community`, node-property-existence constraints are written commented out | | `--render` | | After `mermaid` or `d2` generation, call `mmdc` or `d2` to write an `.svg` | | `--repl` | | Start the interactive REPL (same as `-t repl`) | | `--cnf` | | Print the clausal normal form of the (linted) ontology to stdout and exit | @@ -32,9 +33,11 @@ ontologic-exe [-i|--input FILE] [-t|--target TARGET] [-o|--output PATH] | `--explain-unsat` | | With `--solve`: on UNSAT print the unsatisfiable core | | `--inspect-model` | | With `--solve`: on SAT print the full model valuation | | `--free-constants` | | Treat undeclared free variables in axioms as `Entity` constants (applied before linting and solving) | -| `-T`, `--solve-timeout` | SECONDS | Positive integer. Enforced for z3, cvc5, vampire, and native | +| `-T`, `--solve-timeout` | SECONDS | Positive integer. Enforced for z3, cvc5, vampire, and native. Default 60 seconds when not given; very large values are clamped | | `--solve-memory` | MB | Positive integer. Z3 only; ignored with a warning for other provers | | `--lib-path` | DIR | Extra import search directory; repeatable. Also `$ONTOLOGIC_PATH` | +| `--allow-absolute-imports` | | Allow `(import "/abs/path/file.logic")`. Without it absolute import paths are refused. Relative `../` imports always work. Every import must name a `.logic` file | +| `--version` | | Print `ontologic 1.8.4` and exit | ## Which mode runs @@ -44,7 +47,7 @@ Checked in this order after the file loads and lints cleanly: 2. `--repl` or `-t repl`: start the REPL (no input needed). 3. Otherwise `-i` is required (`Error: --input is required (or use --repl / --lsp)`, exit 1). 4. Load the file and its imports. Failure: parse or import error printed, exit 1. -5. Lint. Any error: errors printed, exit 1. Nothing further runs. +5. Lint. Any error: errors printed, exit 1. Nothing further runs. Warnings (for example from the propositional pass) are printed but do not stop the run. 6. `--cnf`: print CNF, exit 0. 7. `--solve` or `-t solve`: run the solver. 8. Otherwise the target: `lint` (the default) prints `✅ Logic Validated successfully.`; an emitter writes files into `-o`. @@ -94,7 +97,7 @@ External solvers (`z3`, `cvc5`, `vampire`) and renderers (`d2`, `mmdc`) are loca |------|------| | 0 | Lint passed; files emitted; `--cnf` printed; `--solve` found the ontology consistent and every concept satisfiable; REPL/LSP exited normally | | 1 | Missing `--input`; file not found; parse error; import error (not found, circular); any lint error; unknown target; missing `-o`; unknown `--prover`; `--solve` reported UNSAT, empty concepts, or a solver error | -| 2 | `--solve` was inconclusive: the solver answered `unknown` (including a timeout), or the coherence check could not run | +| 2 | `--solve` was inconclusive: the solver answered `unknown` (including a timeout, the native prover meeting equality, or axioms that were not sent to the solver when the rest is satisfiable), or the coherence check could not run | Command-line parse errors (for example a non-positive `-T`) print the message plus usage and exit 1. For `--solve` with several results, the worst wins (1 over 2 over 0), which makes it safe in CI: diff --git a/docs/user-guide/editor-and-lsp.md b/docs/user-guide/editor-and-lsp.md index 8416bfb..d38c3fc 100644 --- a/docs/user-guide/editor-and-lsp.md +++ b/docs/user-guide/editor-and-lsp.md @@ -11,19 +11,19 @@ Capabilities reported by `initialize`: | Diagnostics | Published on open and on every change. Parse errors, plus all linter findings with line and column (`source: ontologic-linter`). Imports are resolved first, so a concept defined in an imported file is not reported as undeclared; problems that belong to the imported files are not shown on yours | | Completion | Triggered on `(`, space, and `"`. Offers keywords, primitive types, and the concepts, properties, and relations of the document and its imports | | Hover | Concepts (parent, properties), properties (domain, type, cardinality, default), relations, and keywords (syntax summary). Comment lines directly above a `def-concept` or `def-property` appear as documentation | -| Go to definition | Jumps to the `def-concept`, `def-property`, or `def-relation` line for the symbol under the cursor, in the open document (not into imported files) | +| Go to definition | Jumps to the `def-concept`, `def-property`, or `def-relation` line for the symbol under the cursor, in the open document or, when the symbol comes from an import, in the imported file | | Rename | `prepareRename` and `rename` of concepts, properties, and relations across the document; rejects keywords and invalid names | | Formatting | Re-indents the whole document (honours the editor's tab size) | | Semantic tokens | Keyword, type, class, property, function, variable, string, number, comment, operator | | Code actions | Quick-fix entries "Verify SMT Consistency", "Explain SMT Unsatisfiable Core", "Inspect SMT Satisfying Model" | | Execute command | `ontologic.solve`, `ontologic.explainUnsat`, `ontologic.inspectModel`. They run asynchronously with progress notifications and can be cancelled; they always use the `auto` prover. When `auto` falls back to the native prover on an ontology with numeric comparisons, the `ontologic.solve` SAT `details` end with a warning that the theory was checked without arithmetic | -Imports use the same search path as the CLI, including `$ONTOLOGIC_PATH` (set it in the environment the editor is launched from). The server has no `--lib-path` option. +Imports use the same search path as the CLI, including `$ONTOLOGIC_PATH` (set it in the environment the editor is launched from). The server has no `--lib-path` option. Solver commands use the same 60 second default limit as the CLI. -A diagnostic exchange, abbreviated: +The completion keyword list does not yet include `def-individual`, `def-axiom`, `if` or the comparison operators, and the server does not answer `textDocument/references` or `documentSymbol` requests. A diagnostic exchange, abbreviated: ```json -{"method":"textDocument/publishDiagnostics","params":{"uri":"file:///tmp/bad.logic","diagnostics":[{"range":{"start":{"line":3,"character":13},"end":{"line":3,"character":100}},"severity":1,"source":"ontologic-linter","message":"Semantic contradiction: Concept Hybrid implies both Truck and Car, but Truck is disjoint with Car."}]}} +{"method":"textDocument/publishDiagnostics","params":{"uri":"file:///tmp/bad.logic","diagnostics":[{"range":{"start":{"line":3,"character":13},"end":{"line":3,"character":100}},"severity":1,"source":"ontologic-linter","message":"Undeclared parent concept: Vehcle referenced by Truck"}]}} ``` ## VS Code extension diff --git a/docs/user-guide/faq.md b/docs/user-guide/faq.md index 900ffc1..84fcdd3 100644 --- a/docs/user-guide/faq.md +++ b/docs/user-guide/faq.md @@ -3,13 +3,13 @@ Short answers to common questions, with links to the pages that go deeper. **What is OntoLogic for?** -Writing a domain model once as first-order logic, proving it is consistent, and generating the code, schemas, and diagrams from it so they cannot drift apart. See the [Quickstart](quickstart.md). +Writing a domain model once as first-order logic, proving it is consistent, and generating the code, schemas, and diagrams from it so that they stay aligned. The aim is that the generated artifacts do not drift from the model, but that is not fully achieved yet: some axioms are not enforced by every target and a few outputs are lossy. See [what is and is not enforced](targets-and-emitters.md#what-is-and-is-not-enforced-or-exported). See the [Quickstart](quickstart.md). **Is the language Prolog or Datalog?** No. Axioms are full first-order logic (disjunction, negation, existentials), not restricted to Horn clauses. See [Axioms and reasoning](axioms-and-reasoning.md) and [../dev/design/constraint_considerations.md](../dev/design/constraint_considerations.md). **Do I need Z3, CVC5, or Vampire?** -No. Without any of them `--prover auto` uses a built-in native prover. But the native prover does not reason about numeric bounds like `(gt level 10)`, so install Z3 or CVC5 if your properties have numeric constraints. See [Installation](installation.md). +No. Without any of them `--prover auto` uses a built-in native prover. The native prover catches clashing numeric bounds (such as `(gte level 100)` with `(lt level 50)`), but integer gaps, and anything involving equality (it answers unknown), need Z3 or CVC5, so install one of them if your properties have numeric constraints. See [Installation](installation.md). **Which prover should I use?** Z3 for most ontologies; CVC5 as a second opinion; Vampire for heavy first-order reasoning without arithmetic; native when nothing is installed. If provers disagree, trust UNSAT from an SMT solver. @@ -72,7 +72,7 @@ In the REPL, `:prove Truck Vehicle`. See [REPL](repl.md). Diagnostics carry the file and line of the declaration (`examples/domain_mining.logic:49:15: error: ...`), even when the root file is a different one. **Which version am I running?** -The package version is in `package.yaml` and [../../CHANGELOG.md](../../CHANGELOG.md). The CLI has no `--version` flag. +Run `ontologic --version`; it prints `ontologic 1.8.4`. The REPL banner shows the same number. The history is in [../../CHANGELOG.md](../../CHANGELOG.md). **Where do I report problems or contribute?** See the contributor workflow in the repository's `AGENTS.md`; the pre-push gate is `stack test --ghc-options="-Wall -Werror"`. diff --git a/docs/user-guide/installation.md b/docs/user-guide/installation.md index dc49c59..ea1eb54 100644 --- a/docs/user-guide/installation.md +++ b/docs/user-guide/installation.md @@ -2,10 +2,16 @@ OntoLogic is built with Stack (GHC 9.4.8, resolver `lts-21.25`) and produces two executables: `ontologic-exe` (compiler, solver driver, REPL) and `ontologic-lsp` (language server). SMT/ATP solvers (Z3, CVC5, Vampire) and diagram renderers (`d2`, `mmdc`) are optional external programs: without a solver OntoLogic falls back to a built-in native prover, and without a renderer it still writes the diagram source. +## Ways to get OntoLogic + +- **Build from source with Stack.** This is the supported path and the one the rest of this guide assumes. The first build downloads GHC 9.4.8 and compiles every dependency, so expect it to take a while. +- **Use a release tarball.** `scripts/package_release.sh` builds one (still with Stack, on your machine). If a tarball is attached to a GitHub release for your platform, you can download it, unpack it and copy `bin/ontologic` onto your `PATH` without installing Stack. No prebuilt binary is promised for every platform, so check the project's releases page and fall back to a source build. +- **Docker.** There is no OntoLogic image. + ## Build from source ```bash -git clone <repository-url> OntoLogic +git clone https://github.com/bsommers/OntoLogic.git OntoLogic cd OntoLogic stack build stack exec ontologic-exe -- --help @@ -18,10 +24,14 @@ stack install ontologic-exe --help ``` -Before contributing, the project's gate is `stack test --ghc-options="-Wall -Werror"`; `scripts/check_coverage.sh` runs the suite with coverage. +Before contributing, the project's gate is `stack test --ghc-options="-Wall -Werror"`; `scripts/check_coverage.sh` runs the suite with coverage. Both run on your machine; GitHub does not run them automatically (see [AGENTS.md](../../AGENTS.md)). Release tarballs (built by `scripts/package_release.sh`) lay out `bin/ontologic`, `bin/ontologic-lsp`, `ontologic-lib/`, `examples/`, and the `.vsix`. The CLI in a tarball is named `ontologic`; everywhere in this guide `ontologic-exe` and `ontologic` are the same program. In that layout the standard library is found automatically (see [Standard library](standard-library.md)). +### The `setup.sh` helper + +The repository's `setup.sh` is an optional convenience for Debian or Ubuntu machines. It uses `sudo apt` to install Stack and Docker tooling, and SDKMAN to install Java and Gradle for the `models-java` subproject. You do not need it to build or use OntoLogic; read it before running it, because it changes your system. + ## Optional solvers OntoLogic talks to solvers by running them as child processes found on `PATH`. @@ -38,7 +48,9 @@ With `--prover auto` (the default) OntoLogic tries `z3`, then `cvc5`, then `vamp z3 --version && cvc5 --version && vampire --version ``` -Note that the native prover does not reason about numeric comparisons such as `(gt balance 100)`, so numeric contradictions are only found by Z3 or CVC5. See [Axioms and reasoning](axioms-and-reasoning.md). +Since 1.8.3 the native prover also catches numeric bound conflicts such as `(gt balance 100)` together with `(lt balance 50)`. Only integer gaps (for example no whole number between 1 and 2) need Z3 or CVC5. The native prover does not reason about equality: if the theory uses equality it answers "unknown" instead of guessing. See [Axioms and reasoning](axioms-and-reasoning.md). + +Every backend has a default time limit of 60 seconds; change it with `-T SECONDS`. A solver that crashes, prints an error, or gives no clear answer is reported as a solver error with a non-zero exit code. It is never reported as satisfiable. ## Optional diagram renderers @@ -49,15 +61,15 @@ Note that the native prover does not reason about numeric comparisons such as `( If a renderer is missing, generation still succeeds and a warning is printed. Details in [Visualization](visualization.md). -## Docker +## Neo4j (optional) -There is no OntoLogic image. The repository's `docker-compose.yml` starts a Neo4j 5.12 container and a Python validator container (`Dockerfile.python`, which mounts `./generated/python`) for trying the `neo4j` and `python` targets: +The `neo4j` target writes Cypher files; it does not need a running database. To try them, start any Neo4j instance you like, for example: ```bash -docker-compose up +docker run --rm -p 7474:7474 -p 7687:7687 -e NEO4J_AUTH=neo4j/choose-a-password neo4j:5 ``` -Neo4j listens on ports 7474 (web UI) and 7687 (Bolt); set `NEO4J_AUTH` to change the default credentials. +Then load `graph.cypher` through the web UI on port 7474 or with `cypher-shell`. ## VS Code extension @@ -68,6 +80,8 @@ The extension (`editors/vscode`) adds highlighting, snippets, diagnostics, hover code --install-extension editors/vscode/ontologic-*.vsix ``` +The packaged file is named after the version in `editors/vscode/package.json` (1.8.4 for this release). + The extension needs the `ontologic-lsp` binary: put it on `PATH` (for example via `stack install`) or set `ontologic.lsp.path`. See [Editor and LSP](editor-and-lsp.md). ## Verify the install diff --git a/docs/user-guide/language-reference.md b/docs/user-guide/language-reference.md index 491df34..37d57fd 100644 --- a/docs/user-guide/language-reference.md +++ b/docs/user-guide/language-reference.md @@ -40,7 +40,7 @@ Declares a concept (class). With a parent it is a subclass; the parent must be d (def-property name Domain Type [:cardinality C] [:optional True|False] [:default V]) ``` -A typed attribute of the domain concept. Types: `Integer`, `Float`, `Double`, `Boolean`, `String`; any other name is a custom type, treated as a reference to another concept (an entity-valued property, which the solver models as a relation). +A typed attribute of the domain concept. Types: `Integer`, `Float`, `Double`, `Boolean`, `String`; any other name must be a declared concept and is treated as a reference to it (an entity-valued property, which the solver models as a relation). A name that is not a declared concept, such as `Int` or `DateTime`, is a lint error (`Undeclared property type`). Options can be given in any order: @@ -71,7 +71,7 @@ A relation between concepts. The first two concepts are domain and range; any fu (def-relation drives Driver Vehicle :cardinality 0..*) ``` -Domain and range must be declared concepts. +Domain and range must be declared concepts; an undeclared range is a lint error. ### `def-individual` @@ -93,7 +93,7 @@ Declares a named individual (a constant), optionally typed by a concept. Individ (namespace prefix) ``` -Declares a prefix and optionally its IRI. The prefix is a bare identifier, not a quoted string (`(namespace "bfo" "...")` is a parse error). The first declared namespace becomes the default base IRI for the `owl` and `shacl` targets (override with `--base-iri`). Duplicate prefixes are lint errors. Prefixes are conventionally used in concept names (`bfo:Entity`) but a name containing `:` is just an identifier; nothing expands it. +Declares a prefix and optionally its IRI. The prefix is a bare identifier, not a quoted string (`(namespace "bfo" "...")` is a parse error). The first declared namespace becomes the default base IRI for the `owl` and `shacl` targets (override with `--base-iri`). Declaring one prefix with two different URIs is a lint error (`Duplicate namespace prefix declaration`); repeating the same prefix with the same URI is fine. Prefixes are conventionally used in concept names (`bfo:Entity`) but a name containing `:` is just an identifier; nothing expands it. ### `import` @@ -101,7 +101,7 @@ Declares a prefix and optionally its IRI. The prefix is a bare identifier, not a (import "relative/or/library/file.logic") ``` -Loads another `.logic` file and merges its declarations and axioms. See [Imports and search path](#imports-and-search-path). +Loads another `.logic` file and merges its declarations and axioms. The path must name a `.logic` file; anything else is refused. See [Imports and search path](#imports-and-search-path). ## Axioms @@ -133,7 +133,7 @@ The optional label is documentation only. | `(eq a b)` or `(= a b)` | equality | | `(!= a b)` | disequality | | `(gt p v)` `(gte p v)` `(lt p v)` `(lte p v)` `(ne p v)` `(eq p v)` | comparison of a property with a value | -| `top`, `true`, `bottom`, `false` | truth and falsity (any capitalization of the first letter) | +| `top`, `true`, `bottom`, `false` | truth and falsity (any capitalization of the first letter). They may appear anywhere a formula may, for example `(implies P false)` or `(not false)` | Subformulas of connectives must be parenthesized or one of the constants above. @@ -179,7 +179,7 @@ Axioms of the shape `forall x. Concept(x) implies <comparisons>` are the ones em 6. `./ontologic-lib` in the current directory (running from a source checkout). 7. The current directory, last, so a stray file there cannot shadow a library module. -Only directories that exist are searched. An absolute import path is used as is. Imports are transitive, imported files may import others, and a file imported by several paths is loaded once. A circular import is reported: +Only directories that exist are searched. Absolute import paths are refused unless you pass `--allow-absolute-imports`. Relative paths with `../` are allowed. Imports are transitive, imported files may import others, and a file imported by several paths is loaded once. A circular import is reported: ```text Circular import dependency detected: /path/a.logic -> /path/b.logic -> /path/a.logic @@ -205,11 +205,15 @@ The REPL's `:load` uses the default search path but has no `--lib-path`; set `ON | Check | Example message | |-------|-----------------| -| Undeclared parent / domain / range | `Undeclared parent concept: B referenced by A` | +| Undeclared parent / domain / range / property type | `Undeclared parent concept: B referenced by A`; `Undeclared range concept`; `Undeclared property type` | +| Duplicate namespace prefix | `Duplicate namespace prefix declaration: bfo` | +| Undeclared predicate or property name in an axiom | warning, not an error | | Duplicates | `Duplicate concept definition: Bus` | | Circular inheritance | `Circular inheritance: ...` | | Contradictory bounds | `Property contradiction on methane_level: gt 5 and lt 3` | | Inherited-bound clash | `Cross-axiom contradiction on GasSensor.methane_level: ...` | -| Disjointness violation | `Semantic contradiction: Concept Hybrid implies both Truck and Car, but Truck is disjoint with Car.` | +| Disjointness violation (warning) | `Semantic contradiction: Concept Hybrid implies both Truck and Car, but Truck is disjoint with Car.` | + +Structural findings (undeclared symbols and types, duplicates, cycles) and numeric bound contradictions are errors and give exit code 1. The disjointness row comes from the propositional pass, which only warns: it prints `warning:` and exits 0. The solver (`--solve`) is the authority on whether the ontology is consistent. Next: [Axioms and reasoning](axioms-and-reasoning.md) diff --git a/docs/user-guide/quickstart.md b/docs/user-guide/quickstart.md index 1bf3576..0c8d58b 100644 --- a/docs/user-guide/quickstart.md +++ b/docs/user-guide/quickstart.md @@ -44,7 +44,7 @@ stack exec ontologic-exe -- -i fleet.logic -t lint ✅ Logic Validated successfully. ``` -The linter checks symbols, duplicates, inheritance cycles, and obvious contradictions. Try breaking it: make `Hybrid` a subclass of `Truck` that is also a `Car`. +The linter checks symbols, duplicates, inheritance cycles, and obvious contradictions. Structural problems are errors; findings from the logical (propositional) pass are warnings. Try breaking it: make `Hybrid` a subclass of `Truck` that is also a `Car`. ```lisp (def-concept Hybrid Truck) @@ -52,10 +52,10 @@ The linter checks symbols, duplicates, inheritance cycles, and obvious contradic ``` ```text -bad.logic:4:14: error: Semantic contradiction: Concept Hybrid implies both Truck and Car, but Truck is disjoint with Car. +bad.logic:4:14: warning: Semantic contradiction: Concept Hybrid implies both Truck and Car, but Truck is disjoint with Car. ``` -The message has `file:line:col: error:` format, the exit code is 1, and (because the linter runs first) nothing else is attempted. In the real output the file path is printed in full. +The message has `file:line:col: warning:` format. It is a warning, so the exit code stays 0 and the run continues; `--solve` is the check that decides whether `Hybrid` can have instances. Structural mistakes, such as a misspelled parent concept, are `error:` lines with exit code 1, and nothing else is attempted. In the real output the file path is printed in full. ## 3. Solve @@ -108,7 +108,7 @@ fleet.logic:17:2: warning: [WUnmappedAxiom] forall v (Truck(v) implies not Car(v Generated TypeScript/Zod models in out/ts ``` -The warning is expected: the disjointness axiom is logic, not a field bound, so no field constraint can express it. It is recorded as a comment at the end of the generated file. Field bounds were mapped: +The warning is expected: the disjointness axiom is logic, not a field bound, so no field constraint can express it. It is recorded as a comment at the end of the generated file. Field bounds were mapped (the file also holds `CarSchema` and `DriverSchema`, omitted here): ```ts // out/ts/models.ts @@ -117,10 +117,12 @@ export const VehicleSchema = z.object({ speed: z.number().int().gte(0).lte(130), }); export const TruckSchema = VehicleSchema.extend({ - max_load: z.number().int().optional(), + max_load: z.number().int().gte(0).optional(), }); ``` +The generated TypeScript needs the `zod` package. Other targets have their own runtime needs; see [what generated code needs](targets-and-emitters.md#what-generated-code-needs-at-runtime). + ```sql -- out/sql/schema.sql CREATE TABLE IF NOT EXISTS "Vehicle" ( @@ -158,7 +160,7 @@ stack exec ontologic-exe -- --repl ontologic> :load fleet.logic ✅ Loaded fleet.logic (4 concepts, 0 lint errors). ontologic> :prove Truck Vehicle -✅ Theorem Proved via Z3: 'Truck' ⊑ 'Vehicle' (Every instance of Truck is necessarily a Vehicle). +✅ Theorem Proved via Auto (Z3/CVC5/Vampire/Native): 'Truck' ⊑ 'Vehicle' (Every instance of Truck is necessarily a Vehicle). ``` See [REPL](repl.md). diff --git a/docs/user-guide/repl.md b/docs/user-guide/repl.md index a55cda5..86f336a 100644 --- a/docs/user-guide/repl.md +++ b/docs/user-guide/repl.md @@ -4,13 +4,13 @@ The REPL is an interactive session in which you load or type ontology forms, lin ```text ╔════════════════════════════════════════════════════════════╗ -║ OntoLogic Interactive REPL v1.0 ║ +║ OntoLogic Interactive REPL v1.8.4 ║ ║ Type ':help' for commands or enter DSL expressions ║ ╚════════════════════════════════════════════════════════════╝ ontologic> ``` -Input is read one line at a time, so each form or command must fit on one line. End the session with `:quit`, `:q`, `exit`, or end-of-input (Ctrl-D). +The version in the banner is the same number `ontologic --version` prints. Input is read one line at a time, so each form or command must fit on one line. End the session with `:quit`, `:q`, `exit`, or end-of-input (Ctrl-D). ## Commands @@ -34,7 +34,7 @@ Input is read one line at a time, so each form or command must fit on one line. | `:clear` | Empty the session (the prover choice is kept) | | `:quit`, `:q`, `exit` | Leave | -Anything that is not a command is parsed as DSL. A line may contain one or several top-level forms; they are merged into the session. The linter runs after each addition and, if it finds a problem, prints `⚠️ Lint warning: ...` for the first one; the forms stay in the session regardless. +Anything that is not a command is parsed as DSL. A line that starts with `:` but is not a command prints an "unknown command" message (type `:help` for the list) instead of a parse error. A line may contain one or several top-level forms; they are merged into the session. The linter runs after each addition and, if it finds a problem, prints `⚠️ Lint warning: ...` for the first one; the forms stay in the session regardless. The `native` and `vampire` provers have no arithmetic. When one of them is active (or `auto` has no external solver to use) and the session uses `gt`, `gte`, `lt` or `lte`, an all-clear from `:solve`, `:model`, `:explain`, `:unsat` or `:prove` ends with `⚠️ ... checks this theory without arithmetic ...`. Confirm such an answer with `:prover z3` or `:prover cvc5`. @@ -89,8 +89,9 @@ ontologic> :prove Vehicle Truck ## Differences from the CLI - `:load` does not take `--lib-path`; use `ONTOLOGIC_PATH`. +- The time limit defaults to 60 seconds, as on the CLI, but there is no flag to change it here. - `:load` loads even when there are lint errors (it reports `Loaded ... with N lint warnings`); the CLI refuses to continue past lint errors. -- There are no `-T`/`--solve-timeout` or `--solve-memory` controls; for bounded runs use the CLI. +- There are no `-T`/`--solve-timeout` or `--solve-memory` controls; for other time limits use the CLI. - `:solve` always prints the model on SAT; the CLI needs `--inspect-model`. - `:prove` exists only here. - Malformed input prints a parse error with a caret and leaves the session unchanged: @@ -105,4 +106,10 @@ ontologic> (oops unexpected end of input ``` +## Finding library names and scripting + +To see what a library module offers, load it and list it: `:load ontologic-lib/mitre_attack.logic` (or any file on the search path) and then `:show` lists the concepts, properties and relations, including their prefixes such as `bfo:MaterialEntity`. + +The REPL reads standard input, so you can script it: `printf ':load model.logic\n:solve\n:unsat\n' | ontologic-exe --repl`. Remember that `:prove` and `:unsat` exist only in the REPL, so a CI job that needs them has to pipe commands like this. + Next: [Editor and LSP](editor-and-lsp.md) diff --git a/docs/user-guide/targets-and-emitters.md b/docs/user-guide/targets-and-emitters.md index 8e5ddb9..dff8885 100644 --- a/docs/user-guide/targets-and-emitters.md +++ b/docs/user-guide/targets-and-emitters.md @@ -14,6 +14,8 @@ Each `-t <target>` compiles the checked ontology into one or more files in the ` Type mapping: `Integer` becomes the target's 64-bit integer (`int`, `i64`, `int64_t`, `Int` or `integer`); `Float`/`Double` become floating point; `Boolean`, `String` map to the native types; a custom type is a reference to a concept. +Conditional axioms of the form `(forall (x) (implies (and (C x) (eq prop value)) (gt other n)))` are enforced as real `if` checks in the Python, Java, Rust, Go and TypeScript output, and carry a real premise in SHACL. Anything a target cannot express is never silently turned into `true`: it becomes an "unmapped" comment in the output and is listed by `--warn-unmapped`. A relation you declare with the name `gt`, `gte`, `lt` or `lte` is treated as a relation, not as arithmetic. + Constraints are only *enforced* by targets that have a validation notion (Java Jakarta Validation, Pydantic, Zod, Rust/Go/C++ `validate()`, SQL `CHECK`, JSON Schema, OpenAPI, SHACL). The `smt`, `tptp`, `owl`, and diagram targets describe the model rather than enforce it. Background: [../dev/design/constraints_and_patterned.md](../dev/design/constraints_and_patterned.md). ## Application code @@ -113,7 +115,7 @@ message Driver { ### `sql` (aliases `postgres`, `postgresql`, `ddl`) -`schema.sql`: PostgreSQL DDL. One table per concept with a `TEXT` primary key `id`; subclass tables reference the parent with `ON DELETE CASCADE`; bounds become named `CHECK` constraints; relations become junction tables `rel_<name>`. +`schema.sql`: PostgreSQL DDL. One table per concept with a `TEXT` primary key `id`; subclass tables reference the parent with `ON DELETE CASCADE`; bounds become named `CHECK` constraints; relations become junction tables `rel_<name>`. Today a relation is also written as a `TEXT[]` column on its domain table (for example `"drives" TEXT[]` on `Driver`), so the same relation is represented twice. Treat the junction table as the one to use; cleaning this up is planned for v1.10.0. ```sql CREATE TABLE IF NOT EXISTS "Truck" ( @@ -172,6 +174,33 @@ fof(subclass_Truck_Vehicle, axiom, (! [X] : (is_Truck(X) => is_Vehicle(X)))). `mermaid` writes `class_diagram.mmd`; `d2` writes `diagram.d2`. Both accept `--render`. See [Visualization](visualization.md). +## What generated code needs at runtime + +| Target | Needs | +|--------|-------| +| `python` | Python 3 and Pydantic v2 (`pip install pydantic`) | +| `ts` | Zod (`npm install zod`) | +| `java` | Jakarta Validation API (`jakarta.validation`) and a validator implementation such as Hibernate Validator. Annotations do nothing until you call a `Validator` | +| `rust` | Nothing beyond the standard library. Call `validate()` on a value to run the checks | +| `go` | Nothing beyond the standard library. Call `Validate()` | +| `cpp` | A C++20 compiler. Call `validate()` | +| `sql` | PostgreSQL (uses `TEXT[]`, named `CHECK` constraints) | +| `openapi`, `jsonschema`, `graphql`, `protobuf` | A tool from your own stack that reads the schema | +| `neo4j` | A Neo4j server. Constraints need Enterprise Edition | + +Generated models check field values only when you call the validator; construction alone does not run every check in every language. + +## What is and is not enforced or exported + +| Axiom kind | Solver (`--solve`) | Generated code | +|------------|--------------------|----------------| +| Bounds on a property (`gte`, `lte`, ...) for a concept | checked | enforced where the target has validation | +| Conditional bounds (`eq prop value` premise) | checked | enforced in Python, Java, Rust, Go, TypeScript, SHACL | +| Disjointness | checked | not enforced; no `owl:disjointWith` in OWL output; listed as unmapped | +| Existential ("every Truck has a Site") | checked | not enforced; listed as unmapped | +| Cardinality, `:optional`, `:default` | not sent to the solver | shapes fields and schemas | +| `def-individual` | used by the solver | no target emits it | + ## Unmapped axioms An axiom that is not of the "concept implies property comparisons" shape (disjointness, existentials, relational rules) cannot become a field constraint. Targets with `Unmapped by default = yes` in the [CLI reference](cli-reference.md#targets) print diff --git a/docs/user-guide/troubleshooting.md b/docs/user-guide/troubleshooting.md index f8e8e2b..5165686 100644 --- a/docs/user-guide/troubleshooting.md +++ b/docs/user-guide/troubleshooting.md @@ -18,23 +18,29 @@ This page maps messages and surprising results to causes and fixes. Messages are | `Error: --output is required for target: ts` | Emitter without `-o` | Pass `-o DIR` | | `Unknown target: foo` | Misspelled target | See the list in `--help` or the [CLI reference](cli-reference.md#targets) | | `option -T: expected a positive integer, got '0'` | Zero or negative limit | Use a value of 1 or more | +| An import path error mentioning `.logic` or `--allow-absolute-imports` | Import path does not end in `.logic`, or is absolute | Name a `.logic` file; use a relative path or pass `--allow-absolute-imports` | +| An error about `--neo4j-edition` | Value other than `community` or `enterprise` | Use one of those two | ## Lint errors -All have the form `file:line:col: error: message` and make the run exit 1. +Errors have the form `file:line:col: error: message` and make the run exit 1. The one exception is `Axiom contradiction: bottom (false) asserted.`, which has no position. Warnings have the form `file:line:col: warning: message`; they are printed but the run still exits 0. | Message | Meaning and fix | |---------|-----------------| | `Undeclared parent concept: B referenced by A` | `A`'s parent is not declared. Declare it or fix the name. For library concepts include the prefix: `bfo:MaterialEntity` | | `Undeclared domain concept: X in property p` | The property's domain concept is missing | -| `Undeclared domain/range concept: X in relation r` | A relation endpoint is missing | +| `Undeclared range concept: X in ...` | The property's or relation's range concept is missing | +| `Undeclared domain concept: X in relation r` | A relation endpoint is missing (the range side says `Undeclared range concept`) | +| `Undeclared property type` | A property type such as `Int` or `DateTime` that is neither built in (`Integer`, `Float`, `Double`, `String`, `Boolean`) nor a declared concept. Use `Integer`, or declare the concept | +| `Duplicate namespace prefix declaration: p` | Two `namespace` forms give the same prefix two different URIs. Keep one (repeating the same prefix and URI is fine) | | `Duplicate concept definition: A` | Two differing definitions of one concept (identical repeats are merged silently) | | `Circular inheritance: ["A","B","A"]` | The parent chain loops | | `Property contradiction on p: gt 5 and lt 3` | One axiom demands incompatible bounds | | `Cross-axiom contradiction on C.p: ...` | Axioms (including inherited ones) on a concept's property conflict | -| `Semantic contradiction: Concept H implies both T and C, but T is disjoint with C.` | A subclass of two disjoint concepts. Remove one parent or the disjointness axiom | +| `warning: Semantic contradiction: Concept H implies both T and C, but T is disjoint with C.` | A warning, not an error. A subclass of two disjoint concepts. Remove one parent or the disjointness axiom | | `Axiom contradiction: bottom (false) asserted.` | An axiom reduces to `bottom` | -| `Semantic contradiction: Global axioms derive unsatisfiable conflict: A, B.` | The axioms force these concepts to be empty | +| `warning: Semantic contradiction: Global axioms derive unsatisfiable conflict: A, B.` | A warning. The axioms force these concepts to be empty; `--solve` confirms | +| `warning: ... undeclared predicate/property ...` | An axiom uses a name you did not declare. Check for a typo | Contradictions can be reported twice (once per operand order); fix the first and the pair disappears. @@ -42,9 +48,10 @@ Contradictions can be reported twice (once per operand order); fix the first and | Output | Meaning | |--------|---------| -| `⚠️ N axiom(s) were not sent to the solver` | Those axioms could not be translated (reason in parentheses). The verdict covers the rest. See [Axioms and reasoning](axioms-and-reasoning.md#axioms-that-are-not-sent) | +| `⚠️ N axiom(s) were not sent to the solver` | Those axioms could not be translated (reason in parentheses). If the rest is satisfiable the verdict is unknown (exit 2), not consistent; an UNSAT verdict stands. See [Axioms and reasoning](axioms-and-reasoning.md#axioms-that-are-not-sent) | | `ℹ️ ... --free-constants` | You enabled free-constants mode; undeclared names are treated as constants | -| `SMT Solver Result (unknown): ...` | Exit 2. Timeout or the solver gave up. Raise `-T`, try another `-p`, or simplify the ontology | +| `SMT Solver Result (unknown): ...` | Exit 2. Timeout or the solver gave up (or the native prover met equality, which it does not reason about). Raise `-T` (default 60 seconds), try another `-p`, or simplify the ontology | +| `SMT Solver Error: ...` with solver text | Exit 1. The solver printed an error, could not parse its input, or gave no single clear answer. This is never reported as satisfiable. Run the solver by hand on the `-t smt` or `-t tptp` output to see why | | `SMT Solver Error: Failed to execute Z3 solver: ... Ensure 'z3' is installed and available in PATH.` | You asked for a specific prover (`-p z3`) that is not installed. Install it, or use `-p auto`/`-p native` | | `Unknown prover 'x'. Valid options: z3, cvc5, vampire, native, auto` | Bad `-p` value | | `⚠️ --solve-memory is not supported by CVC5 and is ignored.` | Memory limits apply to Z3 only | @@ -82,7 +89,7 @@ OntoLogic flags the answers this affects. When the ontology uses `gt`, `gte`, `l | REPL form spans several lines and fails | Each REPL line is parsed on its own; put the whole form on one line | | Editor shows no diagnostics | Check the "OntoLogic" output channel; run "OntoLogic: Restart Language Server"; make sure `ontologic-lsp` is found (set `ontologic.lsp.path`) | | Editor reports undeclared library concepts | `ONTOLOGIC_PATH` must be set in the environment the editor was launched from | -| Snippet expands to code that does not parse | The concept and axiom snippets use an older syntax; see [Editor and LSP](editor-and-lsp.md) | +| REPL says an unknown command | A line starting with `:` that is not a REPL command; `:help` lists them | ## Getting more detail diff --git a/docs/using.md b/docs/using.md index 004e704..fb670b1 100644 --- a/docs/using.md +++ b/docs/using.md @@ -27,7 +27,8 @@ stack test --ghc-options="-Wall -Werror" ``` For a standalone binary, `./scripts/package_release.sh` builds an archive under -`dist/`; extract it and copy `bin/ontologic` onto your `PATH`. Details are in +`dist/` (it needs Stack, Node.js and npm); extract it and copy `bin/ontologic` +onto your `PATH`. Details are in [installation](user-guide/installation.md). ## Write a first ontology @@ -64,10 +65,14 @@ See the [language reference](user-guide/language-reference.md). ontologic -i sensors.logic -t lint ``` -Lint catches undeclared parents, domains and relation endpoints, taxonomy cycles, -duplicate definitions, contradictory axioms, and empty numeric intervals across -axioms. Findings print as `file:line:col: error: message` and the exit code is -non-zero. Add `--warn-unmapped` to see axioms a given target cannot express +Lint catches undeclared parents, domains, ranges and relation endpoints, +undeclared property types (such as `Int` or `DateTime`, which are not types), +taxonomy cycles, duplicate definitions, duplicate namespace prefixes, contradictory axioms and +empty numeric intervals across axioms. Errors +print as `file:line:col: error: message` and the exit code is non-zero. The +propositional pass (a concept forced to be empty by disjointness, for example) +prints `warning:` and does not change the exit code; so does an axiom that uses +an undeclared predicate or property name. Add `--warn-unmapped` to see axioms a given target cannot express instead of having them dropped quietly. ## Prove things about it @@ -84,7 +89,11 @@ ontologic -i sensors.logic --solve --inspect-model # print a satisfying model (which concepts can have no instance). Exit code `0` means both pass, `1` means unsatisfiable or an error, `2` means the solver answered unknown. Axioms the solver encoding cannot express are listed first. With no external prover -installed, `auto` falls back to the built-in native prover. +installed, `auto` falls back to the built-in native prover. The solver fails +closed: a solver error message, a parse failure, or a missing verdict is +reported as an error, never as satisfiable. Without `-T` every backend gets 60 +seconds; very large `-T` values are clamped. The native prover answers unknown +(exit `2`) when the axioms use equality. Other useful switches: `--free-constants` treats undeclared free variables as constants, `--solve-memory MB` limits Z3 memory, and `--cnf` prints the clausal @@ -127,15 +136,17 @@ Visual output: [visualization](user-guide/visualization.md). ## Reuse the standard library ```lisp -(namespace "bfo" "http://purl.obolibrary.org/obo/bfo.owl#") +(namespace bfo "http://purl.obolibrary.org/obo/bfo.owl#") (import "bfo_2020.logic") (import "cco_core.logic") ``` -Library files resolve by bare name. The search order is the importing file's -directory, `$ONTOLOGIC_PATH` (`:`-separated), the directory beside the binary, the -package data directory, `./ontologic-lib`, then the current directory. Add your -own folders with `--lib-path DIR` (repeatable). See the +Library files resolve by bare name. An import must name a `.logic` file. Absolute +paths are refused unless you pass `--allow-absolute-imports`; relative paths such +as `../shared/base.logic` are fine. The search order is the importing file's +directory, each `--lib-path DIR` (repeatable), `$ONTOLOGIC_PATH` (`:`-separated), +the directory beside the binary, the package data directory, `./ontologic-lib`, +then the current directory. Add your own folders with `--lib-path DIR`. See the [standard library](standard-library.md) for what each module contains and the [domain gallery](domains/README.md) for complete models built on it. @@ -179,7 +190,7 @@ formatting, semantic highlighting, and solver commands as code actions. ```bash ./editors/vscode/scripts/build_extension.sh # builds the .vsix -code --install-extension <path-to-built>.vsix +code --install-extension editors/vscode/ontologic-*.vsix ``` For Neovim, point `nvim-lspconfig` at `ontologic-lsp` for `logic` files. See @@ -187,10 +198,12 @@ For Neovim, point `nvim-lspconfig` at `ontologic-lsp` for `logic` files. See ## Integrate with other tools -- **Gradle.** `./gradlew lintOntology` runs the linter; `./gradlew - generateJavaModels` writes Java models into the `models-java` subproject. -- **Docker.** `docker-compose up -d` starts a local Neo4j (ports 7474 and 7687) - for loading generated Cypher. Credentials come from `NEO4J_AUTH`. +- **Gradle.** `./gradlew generateJavaModels` writes Java models into the + `models-java` subproject. `./gradlew lintOntology` only lints the repository's + own `logic/fleet.logic`; it does not lint your model, so call `ontologic -t lint` + directly. +- **Neo4j.** Generated Cypher loads into any Neo4j instance; see + [installation](user-guide/installation.md#neo4j-optional). - **CI.** Run `ontologic -i model.logic -t lint` and `--solve` as gates; both exit non-zero on failure. diff --git a/editors/vscode/CHANGELOG.md b/editors/vscode/CHANGELOG.md index efd37f1..695be25 100644 --- a/editors/vscode/CHANGELOG.md +++ b/editors/vscode/CHANGELOG.md @@ -2,6 +2,17 @@ All notable changes to the "ontologic" extension will be documented in this file. +## [1.8.4] - 2026-11-15 + +### Changed +- Version aligned with the OntoLogic compiler (1.8.4); `package.json`, the lock file and this changelog now agree. +- TextMate grammar rewritten against the real parser: highlights `def-property`, `def-individual`, `def-axiom`, `namespace`, `if`, `ne`, `true`/`false`/`top`/`bottom`, the `:cardinality`, `:optional` and `:default` options, and the `//`, `/* */` and `#| |#` comment forms. Removed forms the language does not have (`axiom`, `subclass-of`, `neq`, `between`, `in`, `=>`, `<=>`, `DateTime`, `Decimal`, `URI`). +- The `import` snippet now inserts a bare library name (`bfo_2020.logic`) that resolves on the search path. +- README: working install steps, build step, and an accurate feature list. + +### Notes since 1.0.0 +- Go to definition follows imports; rename, document formatting, semantic tokens and the explain/inspect/restart commands were added; the `ontologic.cli.path` setting selects the CLI used by the check commands. + ## [1.0.0] - 2026-09-13 ### Initial Release diff --git a/editors/vscode/README.md b/editors/vscode/README.md index 529baf9..a337e5f 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -6,24 +6,31 @@ Official Visual Studio Code extension for **OntoLogic** — First-Order Logic Do ## Features -- 🌟 **Syntax Highlighting**: Full TextMate grammar support for OntoLogic S-expressions, keywords, FOL quantifiers (`forall`, `exists`), comparison operators, types, and comments. -- ⚡ **Language Server Protocol (LSP)**: Powered by `ontologic-lsp`: - - **Real-Time Diagnostics**: Instant feedback on syntax errors and semantic linter issues (cycle detection, undeclared symbols, interval contradictions). - - **Context-Aware Autocompletion**: Keywords, primitive types, concept classes, and properties. - - **Type Definition & Hover**: Hover over concept names to inspect class inheritance and typed bounds. - - **Jump to Definition**: Jump directly to concept declarations across files. -- 🧩 **Code Snippets**: Quick templates for `def-concept` (with or without a parent), `def-property`, `def-relation`, `def-individual`, `forall` bound/range axioms, `exists` axioms, and `import`. -- 🔍 **Interactive SMT Solver Integration**: Trigger Z3 and CVC5 satisfiability checks and concept emptiness tests directly from the editor command palette. +- **Syntax highlighting**: a TextMate grammar for OntoLogic S-expressions: the `def-concept`, `def-property`, `def-relation`, `def-individual`, `def-axiom`, `namespace` and `import` forms, quantifiers (`forall`, `exists`), connectives (`and`, `or`, `not`, `implies`, `if`, `iff`), comparison operators, types, booleans, `top` and `bottom`, the `:cardinality`, `:optional` and `:default` options, and all comment forms (`;`, `//`, `/* */`, `#| |#`). +- **Language Server Protocol (LSP)**, powered by `ontologic-lsp`: + - **Real-time diagnostics**: parse errors and linter findings (errors and warnings). + - **Completion**: keywords, primitive types, concepts, properties and relations. + - **Hover**: class inheritance, typed properties, and the comments written above a declaration. + - **Go to definition**: follows imports into other files. + - **Rename** of concepts, properties and relations, and **document formatting**. + - **Semantic highlighting**. +- **Snippets**: `def-concept` (with or without a parent), `def-property`, `def-relation`, `def-individual`, `forall` bound/range axioms, `exists` axioms, and `import`. +- **Solver commands** in the Command Palette: check SMT consistency and satisfiability, check concept satisfiability, verify consistency, explain the unsatisfiable core, inspect a satisfying model, and restart the language server. --- ## Installation & Setup -1. Install the `ontologic-1.3.0.vsix` extension package: +1. Build and package the extension (needs Node.js and npm; run from the repository root): ```bash - code --install-extension ontologic-1.3.0.vsix + ./editors/vscode/scripts/build_extension.sh ``` -2. Ensure `ontologic-lsp` is in your `PATH` (e.g., `~/.local/bin/ontologic-lsp`) or configure `ontologic.lsp.path` in Settings. + This writes `editors/vscode/ontologic-<version>.vsix`, where the version is the one in `package.json` (1.8.4 for this release). No `.vsix` file is checked in. +2. Install it: + ```bash + code --install-extension editors/vscode/ontologic-*.vsix + ``` +3. Ensure `ontologic-lsp` is in your `PATH` (for example `~/.local/bin/ontologic-lsp` after `stack install`) or set `ontologic.lsp.path` in Settings. --- @@ -32,5 +39,6 @@ Official Visual Studio Code extension for **OntoLogic** — First-Order Logic Do | Setting | Default | Description | | :--- | :--- | :--- | | `ontologic.lsp.path` | `"ontologic-lsp"` | Path to the `ontologic-lsp` binary. | +| `ontologic.cli.path` | empty | Path to the `ontologic` CLI used by the check commands. Empty means: next to the language server, a Stack build in the workspace, then `PATH`. | | `ontologic.solver.prover` | `"auto"` | SMT theorem prover backend (`auto`, `z3`, `cvc5`, `vampire`). | | `ontologic.trace.server` | `"off"` | Trace level for LSP JSON-RPC communication. | diff --git a/editors/vscode/language-configuration.json b/editors/vscode/language-configuration.json index 9cc7891..81cc0f4 100644 --- a/editors/vscode/language-configuration.json +++ b/editors/vscode/language-configuration.json @@ -1,23 +1,63 @@ { "comments": { - "lineComment": ";" + "lineComment": ";", + "blockComment": [ + "/*", + "*/" + ] }, "brackets": [ - ["(", ")"], - ["[", "]"], - ["{", "}"] + [ + "(", + ")" + ], + [ + "[", + "]" + ], + [ + "{", + "}" + ] ], "autoClosingPairs": [ - { "open": "(", "close": ")" }, - { "open": "[", "close": "]" }, - { "open": "{", "close": "}" }, - { "open": "\"", "close": "\"", "notIn": ["string"] } + { + "open": "(", + "close": ")" + }, + { + "open": "[", + "close": "]" + }, + { + "open": "{", + "close": "}" + }, + { + "open": "\"", + "close": "\"", + "notIn": [ + "string" + ] + } ], "surroundingPairs": [ - ["(", ")"], - ["[", "]"], - ["{", "}"], - ["\"", "\""] + [ + "(", + ")" + ], + [ + "[", + "]" + ], + [ + "{", + "}" + ], + [ + "\"", + "\"" + ] ], "wordPattern": "(-?\\d*\\.\\d\\w*)|([^\\`\\~\\!\\@\\#\\%\\^\\&\\*\\(\\)\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\,\\.\\<\\>\\/\\?\\s]+)" } diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json index cfae6ca..4755699 100644 --- a/editors/vscode/package-lock.json +++ b/editors/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "ontologic", - "version": "1.0.0", + "version": "1.8.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ontologic", - "version": "1.0.0", + "version": "1.8.4", "dependencies": { "vscode-languageclient": "^9.0.1" }, diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 05e3593..45e7070 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "ontologic", "displayName": "OntoLogic", "description": "Rich Language Server Protocol, syntax highlighting, snippets, and SMT solver tooling for OntoLogic DSL.", - "version": "1.3.0", + "version": "1.8.4", "publisher": "bsommers", "license": "Apache-2.0", "repository": { diff --git a/editors/vscode/snippets/ontologic.json b/editors/vscode/snippets/ontologic.json index 8120210..e01ec12 100644 --- a/editors/vscode/snippets/ontologic.json +++ b/editors/vscode/snippets/ontologic.json @@ -57,7 +57,7 @@ }, "Import File": { "prefix": "import", - "body": ["(import \"${1:ontologic-lib/bfo_2020.logic}\")$0"], + "body": ["(import \"${1:bfo_2020.logic}\")$0"], "description": "Import an external ontology definition file" } } diff --git a/editors/vscode/syntaxes/ontologic.tmLanguage.json b/editors/vscode/syntaxes/ontologic.tmLanguage.json index 9c8ad02..1f89b17 100644 --- a/editors/vscode/syntaxes/ontologic.tmLanguage.json +++ b/editors/vscode/syntaxes/ontologic.tmLanguage.json @@ -3,14 +3,36 @@ "name": "OntoLogic", "scopeName": "source.ontologic", "patterns": [ - { "include": "#comments" }, - { "include": "#strings" }, - { "include": "#numbers" }, - { "include": "#keywords" }, - { "include": "#operators" }, - { "include": "#types" }, - { "include": "#concepts" }, - { "include": "#identifiers" } + { + "include": "#comments" + }, + { + "include": "#strings" + }, + { + "include": "#numbers" + }, + { + "include": "#options" + }, + { + "include": "#keywords" + }, + { + "include": "#operators" + }, + { + "include": "#constants" + }, + { + "include": "#types" + }, + { + "include": "#concepts" + }, + { + "include": "#identifiers" + } ], "repository": { "comments": { @@ -18,6 +40,20 @@ { "name": "comment.line.semicolon.ontologic", "match": ";.*$" + }, + { + "name": "comment.line.double-slash.ontologic", + "match": "//.*$" + }, + { + "name": "comment.block.ontologic", + "begin": "/\\*", + "end": "\\*/" + }, + { + "name": "comment.block.lisp.ontologic", + "begin": "#\\|", + "end": "\\|#" } ] }, @@ -48,11 +84,11 @@ "patterns": [ { "name": "keyword.declaration.ontologic", - "match": "\\b(def-concept|def-relation|axiom|import|subclass-of)\\b" + "match": "(?<![\\w:.-])(def-concept|def-property|def-relation|def-individual|def-axiom|namespace|import)(?![\\w:.-])" }, { "name": "keyword.control.quantifier.ontologic", - "match": "\\b(forall|exists)\\b" + "match": "(?<![\\w:.-])(forall|exists)(?![\\w:.-])" } ] }, @@ -60,11 +96,11 @@ "patterns": [ { "name": "keyword.operator.logical.ontologic", - "match": "\\b(and|or|not|implies|iff)\\b|=>|<=>" + "match": "(?<![\\w:.-])(and|or|not|implies|if|iff)(?![\\w:.-])" }, { "name": "keyword.operator.comparison.ontologic", - "match": "\\b(gt|gte|lt|lte|eq|neq|between|in)\\b|>|>=|<|<=|=|!=" + "match": "(?<![\\w:.-])(gt|gte|lt|lte|eq|ne)(?![\\w:.-])|(?<=\\()\\s*(=|!=)(?=\\s)" } ] }, @@ -72,7 +108,7 @@ "patterns": [ { "name": "support.type.primitive.ontologic", - "match": "\\b(String|Integer|Float|Double|Boolean|DateTime|Decimal|URI)\\b" + "match": "\\b(String|Integer|Float|Double|Boolean)\\b" } ] }, @@ -91,6 +127,22 @@ "match": "\\b[a-z][a-zA-Z0-9_\\-]*\\b" } ] + }, + "options": { + "patterns": [ + { + "name": "keyword.other.option.ontologic", + "match": "(?<![\\w-]):(cardinality|optional|default)(?![\\w-])" + } + ] + }, + "constants": { + "patterns": [ + { + "name": "constant.language.ontologic", + "match": "(?<![\\w:.-])(true|false|True|False|top|bottom|Top|Bottom)(?![\\w:.-])" + } + ] } } } diff --git a/examples/domain_agriculture.cypher b/examples/domain_agriculture.cypher index 1ea88bf..807c39c 100644 --- a/examples/domain_agriculture.cypher +++ b/examples/domain_agriculture.cypher @@ -365,3 +365,4 @@ MATCH (n:`HarvestLot`) WHERE NOT (n.`has_traceability_lot` = true) RETURN elemen // forall s (MoistureSensor(s) and lt(soil_moisture_percent, 20) implies exists i (IrrigationSystem(i))) // forall a (Livestock(a) and in_quarantine = True implies sold_for_slaughter = False) // forall s (Spraying(s) and pesticide_applied = True implies gte(days_before_harvest, 14)) +// forall l (HarvestLot(l) implies has_traceability_lot = True) diff --git a/examples/domain_agriculture.d2 b/examples/domain_agriculture.d2 index beb387c..b2af28a 100644 --- a/examples/domain_agriculture.d2 +++ b/examples/domain_agriculture.d2 @@ -235,3 +235,4 @@ # forall s (MoistureSensor(s) and lt(soil_moisture_percent, 20) implies exists i (IrrigationSystem(i))) # forall a (Livestock(a) and in_quarantine = True implies sold_for_slaughter = False) # forall s (Spraying(s) and pesticide_applied = True implies gte(days_before_harvest, 14)) +# forall l (HarvestLot(l) implies has_traceability_lot = True) diff --git a/examples/domain_agriculture.mmd b/examples/domain_agriculture.mmd index deec517..671548d 100644 --- a/examples/domain_agriculture.mmd +++ b/examples/domain_agriculture.mmd @@ -236,3 +236,4 @@ classDiagram %% forall s (MoistureSensor(s) and lt(soil_moisture_percent, 20) implies exists i (IrrigationSystem(i))) %% forall a (Livestock(a) and in_quarantine = True implies sold_for_slaughter = False) %% forall s (Spraying(s) and pesticide_applied = True implies gte(days_before_harvest, 14)) +%% forall l (HarvestLot(l) implies has_traceability_lot = True) diff --git a/examples/domain_clinical_medicine.cypher b/examples/domain_clinical_medicine.cypher index ac19539..cb820b5 100644 --- a/examples/domain_clinical_medicine.cypher +++ b/examples/domain_clinical_medicine.cypher @@ -168,9 +168,6 @@ MERGE (n)-[:SUBCLASS_OF]->(p); MERGE (n:OntologyClass {name: 'ClinicalNote'}) MERGE (p:OntologyClass {name: 'InformationContentEntity'}) MERGE (n)-[:SUBCLASS_OF]->(p); -MERGE (n:OntologyClass {name: 'EscalationRecord'}) -MERGE (p:OntologyClass {name: 'InformationContentEntity'}) -MERGE (n)-[:SUBCLASS_OF]->(p); MERGE (n:OntologyClass {name: 'ClinicalOrder'}) MERGE (p:OntologyClass {name: 'InformationContentEntity'}) MERGE (n)-[:SUBCLASS_OF]->(p); @@ -268,8 +265,6 @@ MATCH (n:`Patient`) WHERE NOT (n.`oxygen_saturation` <= 100) RETURN elementId(n) MATCH (n:`Patient`) WHERE NOT (n.`heart_rate` >= 0) RETURN elementId(n) AS invalid_node_id; // Axiom validation: Patient heart_rate lte 300 MATCH (n:`Patient`) WHERE NOT (n.`heart_rate` <= 300) RETURN elementId(n) AS invalid_node_id; -// Axiom validation: Physician is_licensed_prescriber eq True -MATCH (n:`Physician`) WHERE NOT (n.`is_licensed_prescriber` = true) RETURN elementId(n) AS invalid_node_id; // Axiom validation: EmergencyVisit triage_level gte 1 MATCH (n:`EmergencyVisit`) WHERE NOT (n.`triage_level` >= 1) RETURN elementId(n) AS invalid_node_id; // Axiom validation: EmergencyVisit triage_level lte 5 @@ -287,5 +282,8 @@ MATCH (n:`ControlledSubstanceOrder`) WHERE NOT (n.`dose_mg` <= 200) RETURN eleme // forall x (not Patient(x) and Clinician(x)) // forall x (not ClinicalOrder(x) and Observation(x)) // forall x (not Medication(x) and ActiveIngredient(x)) -// forall p (forall a (forall m (forall o (has_allergy(p, a) and triggers_allergy(a, m) and orders_medication(o, m) implies not received_by(o, p))))) -// forall p (Patient(p) and lt(oxygen_saturation, 90) implies exists e (EscalationRecord(e))) +// forall p (forall a (forall m (has_allergy(p, a) and triggers_allergy(a, m) implies not exists o (MedicationOrder(o) and orders_medication(o, m) and received_by(o, p))))) +// forall p (Patient(p) and lt(oxygen_saturation, 90) implies exists n (ClinicalNote(n))) +// forall o (MedicationOrder(o) implies is_signed = True) +// forall c (forall o (prescribes(c, o) implies is_licensed_prescriber = True)) +// forall d (Discharge(d) implies has_summary = True) diff --git a/examples/domain_clinical_medicine.d2 b/examples/domain_clinical_medicine.d2 index 9c253a9..e93a207 100644 --- a/examples/domain_clinical_medicine.d2 +++ b/examples/domain_clinical_medicine.d2 @@ -55,7 +55,6 @@ "ImagingResult": { shape: class } "DischargeSummary": { shape: class } "ClinicalNote": { shape: class } -"EscalationRecord": { shape: class } "ClinicalOrder": { shape: class } "MedicationOrder": { shape: class } "ControlledSubstanceOrder": { shape: class } @@ -128,7 +127,6 @@ "ImagingResult" -> "Observation" "DischargeSummary" -> "InformationContentEntity" "ClinicalNote" -> "InformationContentEntity" -"EscalationRecord" -> "InformationContentEntity" "ClinicalOrder" -> "InformationContentEntity" "MedicationOrder" -> "ClinicalOrder" "ControlledSubstanceOrder" -> "MedicationOrder" @@ -179,5 +177,8 @@ # forall x (not Patient(x) and Clinician(x)) # forall x (not ClinicalOrder(x) and Observation(x)) # forall x (not Medication(x) and ActiveIngredient(x)) -# forall p (forall a (forall m (forall o (has_allergy(p, a) and triggers_allergy(a, m) and orders_medication(o, m) implies not received_by(o, p))))) -# forall p (Patient(p) and lt(oxygen_saturation, 90) implies exists e (EscalationRecord(e))) +# forall p (forall a (forall m (has_allergy(p, a) and triggers_allergy(a, m) implies not exists o (MedicationOrder(o) and orders_medication(o, m) and received_by(o, p))))) +# forall p (Patient(p) and lt(oxygen_saturation, 90) implies exists n (ClinicalNote(n))) +# forall o (MedicationOrder(o) implies is_signed = True) +# forall c (forall o (prescribes(c, o) implies is_licensed_prescriber = True)) +# forall d (Discharge(d) implies has_summary = True) diff --git a/examples/domain_clinical_medicine.mmd b/examples/domain_clinical_medicine.mmd index 1b2eca8..fb3936e 100644 --- a/examples/domain_clinical_medicine.mmd +++ b/examples/domain_clinical_medicine.mmd @@ -56,7 +56,6 @@ classDiagram class ImagingResult["ImagingResult"] class DischargeSummary["DischargeSummary"] class ClinicalNote["ClinicalNote"] - class EscalationRecord["EscalationRecord"] class ClinicalOrder["ClinicalOrder"] class MedicationOrder["MedicationOrder"] class ControlledSubstanceOrder["ControlledSubstanceOrder"] @@ -128,7 +127,6 @@ classDiagram Observation <|-- ImagingResult InformationContentEntity <|-- DischargeSummary InformationContentEntity <|-- ClinicalNote - InformationContentEntity <|-- EscalationRecord InformationContentEntity <|-- ClinicalOrder ClinicalOrder <|-- MedicationOrder MedicationOrder <|-- ControlledSubstanceOrder @@ -180,5 +178,8 @@ classDiagram %% forall x (not Patient(x) and Clinician(x)) %% forall x (not ClinicalOrder(x) and Observation(x)) %% forall x (not Medication(x) and ActiveIngredient(x)) -%% forall p (forall a (forall m (forall o (has_allergy(p, a) and triggers_allergy(a, m) and orders_medication(o, m) implies not received_by(o, p))))) -%% forall p (Patient(p) and lt(oxygen_saturation, 90) implies exists e (EscalationRecord(e))) +%% forall p (forall a (forall m (has_allergy(p, a) and triggers_allergy(a, m) implies not exists o (MedicationOrder(o) and orders_medication(o, m) and received_by(o, p))))) +%% forall p (Patient(p) and lt(oxygen_saturation, 90) implies exists n (ClinicalNote(n))) +%% forall o (MedicationOrder(o) implies is_signed = True) +%% forall c (forall o (prescribes(c, o) implies is_licensed_prescriber = True)) +%% forall d (Discharge(d) implies has_summary = True) diff --git a/examples/domain_customer_service.cypher b/examples/domain_customer_service.cypher index 6c88ae0..aa30418 100644 --- a/examples/domain_customer_service.cypher +++ b/examples/domain_customer_service.cypher @@ -290,3 +290,4 @@ MATCH (n:`InternalRunbook`) WHERE NOT (n.`is_internal_only` = true) RETURN eleme // forall x (not OpenStatus(x) and ClosedStatus(x)) // forall t (Ticket(t) and is_breached = True implies is_escalated = True) // forall t (Ticket(t) and gt(reopen_count, 3) implies is_escalated = True) +// forall k (InternalRunbook(k) implies is_internal_only = True) diff --git a/examples/domain_customer_service.d2 b/examples/domain_customer_service.d2 index 8717f2b..809492d 100644 --- a/examples/domain_customer_service.d2 +++ b/examples/domain_customer_service.d2 @@ -185,3 +185,4 @@ # forall x (not OpenStatus(x) and ClosedStatus(x)) # forall t (Ticket(t) and is_breached = True implies is_escalated = True) # forall t (Ticket(t) and gt(reopen_count, 3) implies is_escalated = True) +# forall k (InternalRunbook(k) implies is_internal_only = True) diff --git a/examples/domain_customer_service.mmd b/examples/domain_customer_service.mmd index c3ff661..9e2253f 100644 --- a/examples/domain_customer_service.mmd +++ b/examples/domain_customer_service.mmd @@ -186,3 +186,4 @@ classDiagram %% forall x (not OpenStatus(x) and ClosedStatus(x)) %% forall t (Ticket(t) and is_breached = True implies is_escalated = True) %% forall t (Ticket(t) and gt(reopen_count, 3) implies is_escalated = True) +%% forall k (InternalRunbook(k) implies is_internal_only = True) diff --git a/examples/domain_customer_success.cypher b/examples/domain_customer_success.cypher index 7d581f1..61a1636 100644 --- a/examples/domain_customer_success.cypher +++ b/examples/domain_customer_success.cypher @@ -306,3 +306,4 @@ MATCH (n:`NPSSurvey`) WHERE NOT (n.`nps_score` <= 10) RETURN elementId(n) AS inv // forall x (not VoluntaryChurn(x) and InvoluntaryChurn(x)) // forall a (Account(a) and lt(health_score, 40) implies is_at_risk = True) // forall a (Account(a) and is_at_risk = True implies has_success_plan = True) +// forall a (EnterpriseAccount(a) implies has_executive_sponsor = True) diff --git a/examples/domain_customer_success.d2 b/examples/domain_customer_success.d2 index 99cd555..3d51919 100644 --- a/examples/domain_customer_success.d2 +++ b/examples/domain_customer_success.d2 @@ -193,3 +193,4 @@ # forall x (not VoluntaryChurn(x) and InvoluntaryChurn(x)) # forall a (Account(a) and lt(health_score, 40) implies is_at_risk = True) # forall a (Account(a) and is_at_risk = True implies has_success_plan = True) +# forall a (EnterpriseAccount(a) implies has_executive_sponsor = True) diff --git a/examples/domain_customer_success.mmd b/examples/domain_customer_success.mmd index e6ed551..fafdab2 100644 --- a/examples/domain_customer_success.mmd +++ b/examples/domain_customer_success.mmd @@ -194,3 +194,4 @@ classDiagram %% forall x (not VoluntaryChurn(x) and InvoluntaryChurn(x)) %% forall a (Account(a) and lt(health_score, 40) implies is_at_risk = True) %% forall a (Account(a) and is_at_risk = True implies has_success_plan = True) +%% forall a (EnterpriseAccount(a) implies has_executive_sponsor = True) diff --git a/examples/domain_cybersecurity_soc.cypher b/examples/domain_cybersecurity_soc.cypher index 0d978b8..7f2caba 100644 --- a/examples/domain_cybersecurity_soc.cypher +++ b/examples/domain_cybersecurity_soc.cypher @@ -356,8 +356,10 @@ MATCH (n:`Incident`) WHERE NOT (n.`minutes_to_acknowledge` <= 240) RETURN elemen // WARNING: The following axioms could not be mapped to field constraints: // forall i (Incident(i) and incident_severity = 4 implies is_escalated = True) +// forall a (PrivilegedAccount(a) implies is_mfa_enabled = True) // forall c (DisableAccount(c) implies exists a (Analyst(a) and approved_by(c, a))) // forall c (IsolateHost(c) implies exists a (Analyst(a) and approved_by(c, a))) +// forall e (Evidence(e) implies chain_of_custody_intact = True) // forall i (Incident(i) implies exists p (Playbook(p) and handled_by_playbook(i, p))) // forall i (Incident(i) and is_closed = True implies has_post_incident_review = True) // forall a (FalsePositiveAlert(a) implies not TruePositiveAlert(a)) diff --git a/examples/domain_cybersecurity_soc.d2 b/examples/domain_cybersecurity_soc.d2 index 7a17ea3..c55d0dd 100644 --- a/examples/domain_cybersecurity_soc.d2 +++ b/examples/domain_cybersecurity_soc.d2 @@ -225,8 +225,10 @@ "Analyst" -> "SocManager": reports_to # WARNING: The following axioms could not be mapped to field constraints: # forall i (Incident(i) and incident_severity = 4 implies is_escalated = True) +# forall a (PrivilegedAccount(a) implies is_mfa_enabled = True) # forall c (DisableAccount(c) implies exists a (Analyst(a) and approved_by(c, a))) # forall c (IsolateHost(c) implies exists a (Analyst(a) and approved_by(c, a))) +# forall e (Evidence(e) implies chain_of_custody_intact = True) # forall i (Incident(i) implies exists p (Playbook(p) and handled_by_playbook(i, p))) # forall i (Incident(i) and is_closed = True implies has_post_incident_review = True) # forall a (FalsePositiveAlert(a) implies not TruePositiveAlert(a)) diff --git a/examples/domain_cybersecurity_soc.mmd b/examples/domain_cybersecurity_soc.mmd index 192b1de..6e7b14c 100644 --- a/examples/domain_cybersecurity_soc.mmd +++ b/examples/domain_cybersecurity_soc.mmd @@ -226,8 +226,10 @@ classDiagram %% WARNING: The following axioms could not be mapped to field constraints: %% forall i (Incident(i) and incident_severity = 4 implies is_escalated = True) +%% forall a (PrivilegedAccount(a) implies is_mfa_enabled = True) %% forall c (DisableAccount(c) implies exists a (Analyst(a) and approved_by(c, a))) %% forall c (IsolateHost(c) implies exists a (Analyst(a) and approved_by(c, a))) +%% forall e (Evidence(e) implies chain_of_custody_intact = True) %% forall i (Incident(i) implies exists p (Playbook(p) and handled_by_playbook(i, p))) %% forall i (Incident(i) and is_closed = True implies has_post_incident_review = True) %% forall a (FalsePositiveAlert(a) implies not TruePositiveAlert(a)) diff --git a/examples/domain_food_service.cypher b/examples/domain_food_service.cypher index ea95676..ed89fde 100644 --- a/examples/domain_food_service.cypher +++ b/examples/domain_food_service.cypher @@ -328,3 +328,4 @@ MATCH (n:`Reheating`) WHERE NOT (n.`reheat_temp_c` >= 74) RETURN elementId(n) AS // forall b (FoodBatch(b) and gt(hours_in_danger_zone, 4) implies is_discarded = True) // forall o (Order(o) and has_allergy_flag = True implies is_allergen_free_prepared = True) // forall m (MenuItem(m) and is_available = True implies contains_allergen_declared = True) +// forall k (KitchenStaff(k) implies food_handler_certified = True) diff --git a/examples/domain_food_service.d2 b/examples/domain_food_service.d2 index 22276f7..6d2d088 100644 --- a/examples/domain_food_service.d2 +++ b/examples/domain_food_service.d2 @@ -213,3 +213,4 @@ # forall b (FoodBatch(b) and gt(hours_in_danger_zone, 4) implies is_discarded = True) # forall o (Order(o) and has_allergy_flag = True implies is_allergen_free_prepared = True) # forall m (MenuItem(m) and is_available = True implies contains_allergen_declared = True) +# forall k (KitchenStaff(k) implies food_handler_certified = True) diff --git a/examples/domain_food_service.mmd b/examples/domain_food_service.mmd index 1dcc8d0..c112159 100644 --- a/examples/domain_food_service.mmd +++ b/examples/domain_food_service.mmd @@ -214,3 +214,4 @@ classDiagram %% forall b (FoodBatch(b) and gt(hours_in_danger_zone, 4) implies is_discarded = True) %% forall o (Order(o) and has_allergy_flag = True implies is_allergen_free_prepared = True) %% forall m (MenuItem(m) and is_available = True implies contains_allergen_declared = True) +%% forall k (KitchenStaff(k) implies food_handler_certified = True) diff --git a/examples/domain_ics.cypher b/examples/domain_ics.cypher index 86e950a..31ec236 100644 --- a/examples/domain_ics.cypher +++ b/examples/domain_ics.cypher @@ -304,6 +304,9 @@ MATCH (n:`FirmwareChange`) WHERE NOT (n.`firmware_signed` = true) RETURN element // WARNING: The following axioms could not be mapped to field constraints: // forall c (SafetyController(c) implies not Plc(c)) +// forall a (CriticalAlarm(a) implies requires_acknowledgement = True) +// forall c (Controller(c) implies is_internet_facing = False) // forall b (Bypass(b) implies exists r (SafetyAuthorityRole(r) and authorised_by(b, r))) // forall t (ProcessTrip(t) and is_tripped = True implies exists i (Interlock(i) and initiates(i, t))) +// forall f (FirmwareChange(f) implies firmware_signed = True) // forall x (Alarm(x) implies not Interlock(x)) diff --git a/examples/domain_ics.d2 b/examples/domain_ics.d2 index 961ce7c..664e011 100644 --- a/examples/domain_ics.d2 +++ b/examples/domain_ics.d2 @@ -188,6 +188,9 @@ "FieldDevice" -> "ProcessUnit": located_in # WARNING: The following axioms could not be mapped to field constraints: # forall c (SafetyController(c) implies not Plc(c)) +# forall a (CriticalAlarm(a) implies requires_acknowledgement = True) +# forall c (Controller(c) implies is_internet_facing = False) # forall b (Bypass(b) implies exists r (SafetyAuthorityRole(r) and authorised_by(b, r))) # forall t (ProcessTrip(t) and is_tripped = True implies exists i (Interlock(i) and initiates(i, t))) +# forall f (FirmwareChange(f) implies firmware_signed = True) # forall x (Alarm(x) implies not Interlock(x)) diff --git a/examples/domain_ics.mmd b/examples/domain_ics.mmd index 0628368..9798435 100644 --- a/examples/domain_ics.mmd +++ b/examples/domain_ics.mmd @@ -189,6 +189,9 @@ classDiagram %% WARNING: The following axioms could not be mapped to field constraints: %% forall c (SafetyController(c) implies not Plc(c)) +%% forall a (CriticalAlarm(a) implies requires_acknowledgement = True) +%% forall c (Controller(c) implies is_internet_facing = False) %% forall b (Bypass(b) implies exists r (SafetyAuthorityRole(r) and authorised_by(b, r))) %% forall t (ProcessTrip(t) and is_tripped = True implies exists i (Interlock(i) and initiates(i, t))) +%% forall f (FirmwareChange(f) implies firmware_signed = True) %% forall x (Alarm(x) implies not Interlock(x)) diff --git a/examples/domain_iiot.cypher b/examples/domain_iiot.cypher index b9b0c50..c76adc1 100644 --- a/examples/domain_iiot.cypher +++ b/examples/domain_iiot.cypher @@ -322,6 +322,7 @@ MATCH (n:`Alert`) WHERE NOT (n.`alert_severity` >= 1) RETURN elementId(n) AS inv MATCH (n:`Alert`) WHERE NOT (n.`alert_severity` <= 5) RETURN elementId(n) AS invalid_node_id; // WARNING: The following axioms could not be mapped to field constraints: +// forall m (TelemetryMessage(m) implies is_encrypted_in_transit = True) // forall a (ConditionAlert(a) implies exists x (Asset(x) and raised_for(a, x))) // forall w (PredictiveWorkOrder(w) implies exists a (Alert(a) and triggers(a, w))) // forall g (EdgeGateway(g) implies exists c (Certificate(c) and authenticated_with(g, c))) diff --git a/examples/domain_iiot.d2 b/examples/domain_iiot.d2 index c253ebe..d9c8002 100644 --- a/examples/domain_iiot.d2 +++ b/examples/domain_iiot.d2 @@ -198,6 +198,7 @@ "EdgeGateway" -> "Certificate": authenticated_with "EdgeGateway" -> "NetworkLink": uplink # WARNING: The following axioms could not be mapped to field constraints: +# forall m (TelemetryMessage(m) implies is_encrypted_in_transit = True) # forall a (ConditionAlert(a) implies exists x (Asset(x) and raised_for(a, x))) # forall w (PredictiveWorkOrder(w) implies exists a (Alert(a) and triggers(a, w))) # forall g (EdgeGateway(g) implies exists c (Certificate(c) and authenticated_with(g, c))) diff --git a/examples/domain_iiot.mmd b/examples/domain_iiot.mmd index ebaa4ca..8ec0de9 100644 --- a/examples/domain_iiot.mmd +++ b/examples/domain_iiot.mmd @@ -199,6 +199,7 @@ classDiagram EdgeGateway --> NetworkLink : uplink %% WARNING: The following axioms could not be mapped to field constraints: +%% forall m (TelemetryMessage(m) implies is_encrypted_in_transit = True) %% forall a (ConditionAlert(a) implies exists x (Asset(x) and raised_for(a, x))) %% forall w (PredictiveWorkOrder(w) implies exists a (Alert(a) and triggers(a, w))) %% forall g (EdgeGateway(g) implies exists c (Certificate(c) and authenticated_with(g, c))) diff --git a/examples/domain_iot_smart_home.cypher b/examples/domain_iot_smart_home.cypher index 23acd71..cc270f3 100644 --- a/examples/domain_iot_smart_home.cypher +++ b/examples/domain_iot_smart_home.cypher @@ -325,8 +325,12 @@ MATCH (n:`PersonalData`) WHERE NOT (n.`retention_days` <= 365) RETURN elementId( MATCH (n:`VideoRecording`) WHERE NOT (n.`is_end_to_end_encrypted` = true) RETURN elementId(n) AS invalid_node_id; // WARNING: The following axioms could not be mapped to field constraints: +// forall i (FirmwareImage(i) implies is_signed = True) +// forall v (VideoRecording(v) implies is_end_to_end_encrypted = True) // forall p (PersonalData(p) and is_shared_with_third_party = True implies exists c (Consent(c) and covers(c, p))) // forall v (VideoRecording(v) implies exists c (ConsentGrant(c) and covers(c, v))) // forall s (SmartSpeaker(s) and is_listening = True implies has_hardware_mute = True) +// forall a (Automation(a) implies runs_unattended = False) +// forall d (SmartDevice(d) implies default_password_changed = True) // forall c (Camera(c) implies not SmartSpeaker(c)) // forall c (ConsentGrant(c) implies not ConsentWithdrawal(c)) diff --git a/examples/domain_iot_smart_home.d2 b/examples/domain_iot_smart_home.d2 index a10e0b2..9913d5e 100644 --- a/examples/domain_iot_smart_home.d2 +++ b/examples/domain_iot_smart_home.d2 @@ -203,8 +203,12 @@ "Consent" -> "PersonalData": covers "SmartDevice" -> "PrivacyPolicy": governed_by # WARNING: The following axioms could not be mapped to field constraints: +# forall i (FirmwareImage(i) implies is_signed = True) +# forall v (VideoRecording(v) implies is_end_to_end_encrypted = True) # forall p (PersonalData(p) and is_shared_with_third_party = True implies exists c (Consent(c) and covers(c, p))) # forall v (VideoRecording(v) implies exists c (ConsentGrant(c) and covers(c, v))) # forall s (SmartSpeaker(s) and is_listening = True implies has_hardware_mute = True) +# forall a (Automation(a) implies runs_unattended = False) +# forall d (SmartDevice(d) implies default_password_changed = True) # forall c (Camera(c) implies not SmartSpeaker(c)) # forall c (ConsentGrant(c) implies not ConsentWithdrawal(c)) diff --git a/examples/domain_iot_smart_home.mmd b/examples/domain_iot_smart_home.mmd index 9b5132a..65f0eed 100644 --- a/examples/domain_iot_smart_home.mmd +++ b/examples/domain_iot_smart_home.mmd @@ -204,8 +204,12 @@ classDiagram SmartDevice --> PrivacyPolicy : governed_by %% WARNING: The following axioms could not be mapped to field constraints: +%% forall i (FirmwareImage(i) implies is_signed = True) +%% forall v (VideoRecording(v) implies is_end_to_end_encrypted = True) %% forall p (PersonalData(p) and is_shared_with_third_party = True implies exists c (Consent(c) and covers(c, p))) %% forall v (VideoRecording(v) implies exists c (ConsentGrant(c) and covers(c, v))) %% forall s (SmartSpeaker(s) and is_listening = True implies has_hardware_mute = True) +%% forall a (Automation(a) implies runs_unattended = False) +%% forall d (SmartDevice(d) implies default_password_changed = True) %% forall c (Camera(c) implies not SmartSpeaker(c)) %% forall c (ConsentGrant(c) implies not ConsentWithdrawal(c)) diff --git a/examples/domain_logistics.cypher b/examples/domain_logistics.cypher index 3bf8831..a298220 100644 --- a/examples/domain_logistics.cypher +++ b/examples/domain_logistics.cypher @@ -355,3 +355,4 @@ MATCH (n:`InternationalShipment`) WHERE NOT (n.`has_customs_declaration` = true) // forall x (not FrozenGoods(x) and ChilledGoods(x)) // forall x (not HazmatStore(x) and ColdStore(x)) // forall s (Shipment(s) and is_delivered = True implies has_proof_of_delivery = True) +// forall s (InternationalShipment(s) implies has_customs_declaration = True) diff --git a/examples/domain_logistics.d2 b/examples/domain_logistics.d2 index e99b63d..a7eebf9 100644 --- a/examples/domain_logistics.d2 +++ b/examples/domain_logistics.d2 @@ -221,3 +221,4 @@ # forall x (not FrozenGoods(x) and ChilledGoods(x)) # forall x (not HazmatStore(x) and ColdStore(x)) # forall s (Shipment(s) and is_delivered = True implies has_proof_of_delivery = True) +# forall s (InternationalShipment(s) implies has_customs_declaration = True) diff --git a/examples/domain_logistics.mmd b/examples/domain_logistics.mmd index 6937249..ae5326e 100644 --- a/examples/domain_logistics.mmd +++ b/examples/domain_logistics.mmd @@ -222,3 +222,4 @@ classDiagram %% forall x (not FrozenGoods(x) and ChilledGoods(x)) %% forall x (not HazmatStore(x) and ColdStore(x)) %% forall s (Shipment(s) and is_delivered = True implies has_proof_of_delivery = True) +%% forall s (InternationalShipment(s) implies has_customs_declaration = True) diff --git a/examples/domain_research_projects.cypher b/examples/domain_research_projects.cypher index 9c9dc1c..6572ea7 100644 --- a/examples/domain_research_projects.cypher +++ b/examples/domain_research_projects.cypher @@ -321,11 +321,13 @@ MATCH (n:`Enrolment`) WHERE NOT (n.`consent_obtained` = true) RETURN elementId(n // WARNING: The following axioms could not be mapped to field constraints: // forall s (HumanSubjectsStudy(s) and study_started = True implies exists a (approved_by_ethics(s, a))) // forall e (Enrolment(e) implies exists c (has_consent(e, c))) +// forall e (Enrolment(e) implies consent_obtained = True) // forall g (Grant(g) and grant_active = True implies exists b (has_budget(g, b))) // forall d (Dataset(d) and data_is_personal = True and data_is_public = True implies data_is_anonymised = True) // forall d (Dataset(d) and data_is_public = True implies has_metadata = True) // forall p (Publication(p) and is_peer_reviewed = True implies exists r (reviewed_by(p, r))) // forall p (Publication(p) and is_peer_reviewed = True implies has_coi_declared = True) +// forall t (ClinicalTrial(t) implies is_preregistered = True) // forall x (not Study(x) and Publication(x)) // forall x (not Organization(x) and Person(x)) // forall x (not RawDataset(x) and ProcessedDataset(x)) diff --git a/examples/domain_research_projects.d2 b/examples/domain_research_projects.d2 index 9274890..7b456f5 100644 --- a/examples/domain_research_projects.d2 +++ b/examples/domain_research_projects.d2 @@ -195,11 +195,13 @@ # WARNING: The following axioms could not be mapped to field constraints: # forall s (HumanSubjectsStudy(s) and study_started = True implies exists a (approved_by_ethics(s, a))) # forall e (Enrolment(e) implies exists c (has_consent(e, c))) +# forall e (Enrolment(e) implies consent_obtained = True) # forall g (Grant(g) and grant_active = True implies exists b (has_budget(g, b))) # forall d (Dataset(d) and data_is_personal = True and data_is_public = True implies data_is_anonymised = True) # forall d (Dataset(d) and data_is_public = True implies has_metadata = True) # forall p (Publication(p) and is_peer_reviewed = True implies exists r (reviewed_by(p, r))) # forall p (Publication(p) and is_peer_reviewed = True implies has_coi_declared = True) +# forall t (ClinicalTrial(t) implies is_preregistered = True) # forall x (not Study(x) and Publication(x)) # forall x (not Organization(x) and Person(x)) # forall x (not RawDataset(x) and ProcessedDataset(x)) diff --git a/examples/domain_research_projects.mmd b/examples/domain_research_projects.mmd index ed7d6dc..eaa341b 100644 --- a/examples/domain_research_projects.mmd +++ b/examples/domain_research_projects.mmd @@ -196,11 +196,13 @@ classDiagram %% WARNING: The following axioms could not be mapped to field constraints: %% forall s (HumanSubjectsStudy(s) and study_started = True implies exists a (approved_by_ethics(s, a))) %% forall e (Enrolment(e) implies exists c (has_consent(e, c))) +%% forall e (Enrolment(e) implies consent_obtained = True) %% forall g (Grant(g) and grant_active = True implies exists b (has_budget(g, b))) %% forall d (Dataset(d) and data_is_personal = True and data_is_public = True implies data_is_anonymised = True) %% forall d (Dataset(d) and data_is_public = True implies has_metadata = True) %% forall p (Publication(p) and is_peer_reviewed = True implies exists r (reviewed_by(p, r))) %% forall p (Publication(p) and is_peer_reviewed = True implies has_coi_declared = True) +%% forall t (ClinicalTrial(t) implies is_preregistered = True) %% forall x (not Study(x) and Publication(x)) %% forall x (not Organization(x) and Person(x)) %% forall x (not RawDataset(x) and ProcessedDataset(x)) diff --git a/examples/domain_science_lab.cypher b/examples/domain_science_lab.cypher index 37961a0..a0e2a75 100644 --- a/examples/domain_science_lab.cypher +++ b/examples/domain_science_lab.cypher @@ -303,6 +303,7 @@ MATCH (n:`CustodyRecord`) WHERE NOT (n.`custody_gap` = false) RETURN elementId(n // forall i (Instrument(i) and gt(days_since_calibration, 365) implies calibration_valid = False) // forall e (forall p (Experiment(e) and follows_protocol(e, p) implies protocol_approved = True)) // forall t (CustodyTransfer(t) implies exists r (recorded_in(t, r))) +// forall r (CustodyRecord(r) implies custody_gap = False) // forall s (Sample(s) and is_biohazard = True implies exists d (handled_under(s, d))) // forall e (Experiment(e) and experiment_complete = True implies gte(replicate_count, 3)) // forall e (forall s (Experiment(e) and uses_sample(e, s) implies is_expired = False)) diff --git a/examples/domain_science_lab.d2 b/examples/domain_science_lab.d2 index 4fa2b0e..e0c892b 100644 --- a/examples/domain_science_lab.d2 +++ b/examples/domain_science_lab.d2 @@ -191,6 +191,7 @@ # forall i (Instrument(i) and gt(days_since_calibration, 365) implies calibration_valid = False) # forall e (forall p (Experiment(e) and follows_protocol(e, p) implies protocol_approved = True)) # forall t (CustodyTransfer(t) implies exists r (recorded_in(t, r))) +# forall r (CustodyRecord(r) implies custody_gap = False) # forall s (Sample(s) and is_biohazard = True implies exists d (handled_under(s, d))) # forall e (Experiment(e) and experiment_complete = True implies gte(replicate_count, 3)) # forall e (forall s (Experiment(e) and uses_sample(e, s) implies is_expired = False)) diff --git a/examples/domain_science_lab.mmd b/examples/domain_science_lab.mmd index ebd7fe7..431bfbb 100644 --- a/examples/domain_science_lab.mmd +++ b/examples/domain_science_lab.mmd @@ -192,6 +192,7 @@ classDiagram %% forall i (Instrument(i) and gt(days_since_calibration, 365) implies calibration_valid = False) %% forall e (forall p (Experiment(e) and follows_protocol(e, p) implies protocol_approved = True)) %% forall t (CustodyTransfer(t) implies exists r (recorded_in(t, r))) +%% forall r (CustodyRecord(r) implies custody_gap = False) %% forall s (Sample(s) and is_biohazard = True implies exists d (handled_under(s, d))) %% forall e (Experiment(e) and experiment_complete = True implies gte(replicate_count, 3)) %% forall e (forall s (Experiment(e) and uses_sample(e, s) implies is_expired = False)) diff --git a/examples/domain_semiconductor_fab.cypher b/examples/domain_semiconductor_fab.cypher index 851a6c6..1577b5e 100644 --- a/examples/domain_semiconductor_fab.cypher +++ b/examples/domain_semiconductor_fab.cypher @@ -389,8 +389,11 @@ MATCH (n:`QualifiedRecipe`) WHERE NOT (n.`is_released` = true) RETURN elementId( MATCH (n:`KillerDefect`) WHERE NOT (n.`is_killer` = true) RETURN elementId(n) AS invalid_node_id; // WARNING: The following axioms could not be mapped to field constraints: +// forall r (QualifiedRecipe(r) implies is_released = True) +// forall t (ProcessTool(t) implies is_qualified = True) // forall s (ProcessStep(s) implies exists r (Recipe(r) and uses_recipe(s, r))) // forall p (Photolithography(p) implies exists r (Reticle(r) and uses_reticle(p, r))) +// forall d (KillerDefect(d) implies is_killer = True) // forall h (HoldOrder(h) implies exists l (Lot(l) and hold_for(h, l))) // forall w (ProductWafer(w) implies not DummyWafer(w)) // forall t (ProcessTool(t) implies not MetrologyTool(t)) diff --git a/examples/domain_semiconductor_fab.d2 b/examples/domain_semiconductor_fab.d2 index eced986..ccf811c 100644 --- a/examples/domain_semiconductor_fab.d2 +++ b/examples/domain_semiconductor_fab.d2 @@ -247,8 +247,11 @@ "WaferMap" -> "Wafer": maps "ProcessStep" -> "ControlPlan": governed_by # WARNING: The following axioms could not be mapped to field constraints: +# forall r (QualifiedRecipe(r) implies is_released = True) +# forall t (ProcessTool(t) implies is_qualified = True) # forall s (ProcessStep(s) implies exists r (Recipe(r) and uses_recipe(s, r))) # forall p (Photolithography(p) implies exists r (Reticle(r) and uses_reticle(p, r))) +# forall d (KillerDefect(d) implies is_killer = True) # forall h (HoldOrder(h) implies exists l (Lot(l) and hold_for(h, l))) # forall w (ProductWafer(w) implies not DummyWafer(w)) # forall t (ProcessTool(t) implies not MetrologyTool(t)) diff --git a/examples/domain_semiconductor_fab.mmd b/examples/domain_semiconductor_fab.mmd index a37f2dc..b2e5c99 100644 --- a/examples/domain_semiconductor_fab.mmd +++ b/examples/domain_semiconductor_fab.mmd @@ -248,8 +248,11 @@ classDiagram ProcessStep --> ControlPlan : governed_by %% WARNING: The following axioms could not be mapped to field constraints: +%% forall r (QualifiedRecipe(r) implies is_released = True) +%% forall t (ProcessTool(t) implies is_qualified = True) %% forall s (ProcessStep(s) implies exists r (Recipe(r) and uses_recipe(s, r))) %% forall p (Photolithography(p) implies exists r (Reticle(r) and uses_reticle(p, r))) +%% forall d (KillerDefect(d) implies is_killer = True) %% forall h (HoldOrder(h) implies exists l (Lot(l) and hold_for(h, l))) %% forall w (ProductWafer(w) implies not DummyWafer(w)) %% forall t (ProcessTool(t) implies not MetrologyTool(t)) diff --git a/examples/dough_factory.cypher b/examples/dough_factory.cypher index 87aa264..4443e18 100644 --- a/examples/dough_factory.cypher +++ b/examples/dough_factory.cypher @@ -45,4 +45,5 @@ MATCH (n:`SecurityCamera`) WHERE NOT (n.`is_recording` = true) RETURN elementId( // WARNING: The following axioms could not be mapped to field constraints: // forall o (Oven(o) and is_active() implies gt(temperature, 100)) +// forall c (SecurityCamera(c) implies is_recording = True) // forall m (Mixer(m) and is_active() implies gt(rpm, 0)) diff --git a/examples/dough_factory.d2 b/examples/dough_factory.d2 index f972d27..f7eaf19 100644 --- a/examples/dough_factory.d2 +++ b/examples/dough_factory.d2 @@ -30,4 +30,5 @@ "PackagingMachine"."items_per_minute": Integer # WARNING: The following axioms could not be mapped to field constraints: # forall o (Oven(o) and is_active() implies gt(temperature, 100)) +# forall c (SecurityCamera(c) implies is_recording = True) # forall m (Mixer(m) and is_active() implies gt(rpm, 0)) diff --git a/examples/dough_factory.mmd b/examples/dough_factory.mmd index c98d803..8faa97f 100644 --- a/examples/dough_factory.mmd +++ b/examples/dough_factory.mmd @@ -31,4 +31,5 @@ classDiagram %% WARNING: The following axioms could not be mapped to field constraints: %% forall o (Oven(o) and is_active() implies gt(temperature, 100)) +%% forall c (SecurityCamera(c) implies is_recording = True) %% forall m (Mixer(m) and is_active() implies gt(rpm, 0)) diff --git a/examples/security_policy.d2 b/examples/security_policy.d2 index b0f2ff0..09d1dd0 100644 --- a/examples/security_policy.d2 +++ b/examples/security_policy.d2 @@ -4,5 +4,6 @@ "TrustedNode" -> "NetworkNode" "UntrustedNode" -> "NetworkNode" +"NetworkNode" -> "NetworkNode": can_access # WARNING: The following axioms could not be mapped to field constraints: # forall n (UntrustedNode(n) implies not can_access(n, AdminPanel)) diff --git a/examples/security_policy.logic b/examples/security_policy.logic index 72d6349..92d530c 100644 --- a/examples/security_policy.logic +++ b/examples/security_policy.logic @@ -2,6 +2,11 @@ (def-concept TrustedNode NetworkNode) (def-concept UntrustedNode NetworkNode) +(def-relation can_access NetworkNode NetworkNode) + +; The protected resource must be declared, or the axiom below cannot be sent to the solver. +(def-individual AdminPanel NetworkNode) + ; Logic: UntrustedNodes cannot communicate with the AdminPanel (forall (n) (implies (UntrustedNode n) diff --git a/examples/security_policy.mmd b/examples/security_policy.mmd index 0df4096..d042e7b 100644 --- a/examples/security_policy.mmd +++ b/examples/security_policy.mmd @@ -4,6 +4,7 @@ classDiagram class UntrustedNode["UntrustedNode"] NetworkNode <|-- TrustedNode NetworkNode <|-- UntrustedNode + NetworkNode --> NetworkNode : can_access %% WARNING: The following axioms could not be mapped to field constraints: %% forall n (UntrustedNode(n) implies not can_access(n, AdminPanel)) diff --git a/examples/smart_factory.d2 b/examples/smart_factory.d2 index 1567cc7..e03740b 100644 --- a/examples/smart_factory.d2 +++ b/examples/smart_factory.d2 @@ -8,5 +8,7 @@ "RobotArm" -> "IndustrialEntity" "IndustrialEntity"."safety_status": Boolean "RobotArm"."axis_count": Integer +"Controller"."active": Boolean # WARNING: The following axioms could not be mapped to field constraints: +# forall r (RobotArm(r) implies axis_count = 6) # forall c (Controller(c) and safety_status = False implies active = False) diff --git a/examples/smart_factory.logic b/examples/smart_factory.logic index 3da8061..eb4ba01 100644 --- a/examples/smart_factory.logic +++ b/examples/smart_factory.logic @@ -7,6 +7,7 @@ ; --- Properties --- (def-property safety_status IndustrialEntity Boolean) (def-property axis_count RobotArm Integer) +(def-property active Controller Boolean) ; --- Axioms --- ; All RobotArms must have exactly 6 axes for this specific factory line diff --git a/examples/smart_factory.mmd b/examples/smart_factory.mmd index 9cdeed7..8a55390 100644 --- a/examples/smart_factory.mmd +++ b/examples/smart_factory.mmd @@ -8,6 +8,8 @@ classDiagram IndustrialEntity <|-- RobotArm IndustrialEntity : +Boolean safety_status RobotArm : +Integer axis_count + Controller : +Boolean active %% WARNING: The following axioms could not be mapped to field constraints: +%% forall r (RobotArm(r) implies axis_count = 6) %% forall c (Controller(c) and safety_status = False implies active = False) diff --git a/ontologic-lib/factory_domain.logic b/ontologic-lib/factory_domain.logic index 38311a4..b000a07 100644 --- a/ontologic-lib/factory_domain.logic +++ b/ontologic-lib/factory_domain.logic @@ -64,8 +64,8 @@ ;; ---------------------------------------------------------------------------- ;; Domain Metadata Properties ;; ---------------------------------------------------------------------------- -(def-property dsf:tenet_number dsf:ConstitutionalTenet Int) -(def-property dsf:standard_number dsf:OperationalStandard Int) -(def-property dsf:poset_tier_level dsf:PosetStratum Int) +(def-property dsf:tenet_number dsf:ConstitutionalTenet Integer) +(def-property dsf:standard_number dsf:OperationalStandard Integer) +(def-property dsf:poset_tier_level dsf:PosetStratum Integer) (def-property dsf:capability_id dsf:CapabilityRecord String) (def-property dsf:verification_command dsf:CapabilityRecord String) diff --git a/ontologic.cabal b/ontologic.cabal index 4fa9b10..9a480d2 100644 --- a/ontologic.cabal +++ b/ontologic.cabal @@ -5,7 +5,7 @@ cabal-version: 1.12 -- see: https://github.com/sol/hpack name: ontologic -version: 1.8.3 +version: 1.8.4 homepage: https://github.com/bsommers/OntoLogic#readme bug-reports: https://github.com/bsommers/OntoLogic/issues author: OntoLogic Team @@ -184,10 +184,13 @@ test-suite ontologic-test ComplianceGRCSpec CppSpec D2Spec + DocSamplesSpec DomainExamplesSpec EcosystemSpec EcosystemUnifiedSpec + EmitterParitySpec ExamplesSpec + FailClosedSpec FOLTheorySpec GoSpec GraphQLSpec @@ -199,6 +202,7 @@ test-suite ontologic-test JavaSpec JsonSchemaSpec LinterSpec + LintSoundnessSpec LSPSpec MainSpec MermaidSpec diff --git a/package.yaml b/package.yaml index a0fc09f..d42efea 100644 --- a/package.yaml +++ b/package.yaml @@ -1,5 +1,5 @@ name: ontologic -version: 1.8.3 +version: 1.8.4 github: "bsommers/OntoLogic" license: Apache-2.0 author: "OntoLogic Team" diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index e609a4d..0000000 --- a/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -pydantic==2.5.2 -neo4j==5.15.0 diff --git a/scripts/check_links.py b/scripts/check_links.py new file mode 100755 index 0000000..bdf27f5 --- /dev/null +++ b/scripts/check_links.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Check relative links in tracked Markdown files and top-level site/*.html pages. + +Exits 1 if any relative link points at a missing file. Links into +site/assets/diagrams/ are generated at build time and are only reported. +Usage: python3 scripts/check_links.py (from anywhere inside the repository) +""" +import os +import re +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +os.chdir(ROOT) +files = subprocess.run(["git", "ls-files"], capture_output=True, text=True, check=True).stdout.split("\n") +targets_files = [f for f in files if f.endswith(".md") or (f.startswith("site/") and f.endswith(".html") and f.count("/") == 1)] +md_link = re.compile(r'\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)') +html_attr = re.compile(r'''(?:href|src)=["']([^"']+)["']''') +SKIP = ("http://", "https://", "mailto:", "#", "data:") +broken, generated = [], [] +checked = 0 +for f in sorted(targets_files): + if not f or not os.path.exists(f): + continue + fence = False + with open(f, encoding="utf-8", errors="replace") as fh: + for i, line in enumerate(fh, 1): + s = line.strip() + if s.startswith("```") or s.startswith("~~~"): + fence = not fence + continue + if fence: + continue + tg = md_link.findall(line) + if f.endswith(".html"): + tg += html_attr.findall(line) + for t in tg: + if t.startswith(SKIP) or t.startswith("<"): + continue + p = t.split("#")[0].split("?")[0] + if not p: + continue + checked += 1 + if p.startswith("/"): + res = os.path.normpath(os.path.join(ROOT, p.lstrip("/"))) + else: + res = os.path.normpath(os.path.join(os.path.dirname(f), p)) + if not os.path.exists(res): + if f.startswith("site/") and "assets/diagrams/" in p: + generated.append(f"{f}:{i} -> {t}") + else: + broken.append(f"{f}:{i} -> {t}") +print(f"files={len(targets_files)} links_checked={checked}") +print("BROKEN:", len(broken)) +print("\n".join(broken)) +print("GENERATED (expected):", len(generated)) +sys.exit(1 if broken else 0) diff --git a/scripts/package_release.sh b/scripts/package_release.sh index d59bd6d..18dd5f6 100755 --- a/scripts/package_release.sh +++ b/scripts/package_release.sh @@ -2,24 +2,25 @@ set -euo pipefail # OntoLogic Standalone Release Packaging Script -VERSION="${1:-$(git describe --tags --abbrev=0 2>/dev/null | tr -d 'v' || echo "1.3.0")}" +VERSION="${1:-$(sed -n 's/^version: *//p' package.yaml | head -n 1)}" +[ -n "$VERSION" ] || { echo "Error: cannot determine VERSION; pass it as the first argument" >&2; exit 1; } DIST_DIR="dist" ARCH="$(uname -m)" OS="$(uname -s | tr '[:upper:]' '[:lower:]')" PACKAGE_NAME="ontologic-v${VERSION}-${OS}-${ARCH}" TARGET_DIR="${DIST_DIR}/${PACKAGE_NAME}" -echo "🔨 Building OntoLogic binary via Stack..." +echo "Building OntoLogic binary via Stack..." stack build --ghc-options="-Wall -Werror -O2" BIN_PATH="$(stack path --local-install-root)/bin/ontologic-exe" LSP_BIN_PATH="$(stack path --local-install-root)/bin/ontologic-lsp" if [ ! -f "$BIN_PATH" ]; then - echo "❌ Error: Binary not found at $BIN_PATH" >&2 + echo "Error: Binary not found at $BIN_PATH" >&2 exit 1 fi -echo "📦 Preparing release bundle in ${TARGET_DIR}..." +echo "Preparing release bundle in ${TARGET_DIR}..." rm -rf "${TARGET_DIR}" "${TARGET_DIR}.tar.gz" mkdir -p "${TARGET_DIR}/bin" "${TARGET_DIR}/ontologic-lib" "${TARGET_DIR}/examples" @@ -32,22 +33,25 @@ if [ -f "$LSP_BIN_PATH" ]; then fi if [ -d "editors/vscode" ]; then - echo "🧩 Packaging VS Code Extension (.vsix)..." - (cd editors/vscode && npm run compile && npx @vscode/vsce package --no-git-tag-version) - mkdir -p "${TARGET_DIR}/editors/vscode" - cp editors/vscode/ontologic-${VERSION}.vsix "${TARGET_DIR}/editors/vscode/" - cp editors/vscode/ontologic-${VERSION}.vsix "${DIST_DIR}/" + echo "Packaging VS Code extension (.vsix)..." + (cd editors/vscode && npm ci && npm run compile && npx @vscode/vsce package) + # vsce names the file after the extension's own version (editors/vscode/package.json), + # which need not equal the compiler version, so take whatever it produced. + VSIX="$(ls -t editors/vscode/*.vsix | head -n 1)" + mkdir -p "${TARGET_DIR}/editors/vscode" "${DIST_DIR}" + cp "$VSIX" "${TARGET_DIR}/editors/vscode/" + cp "$VSIX" "${DIST_DIR}/" fi cp ontologic-lib/*.logic "${TARGET_DIR}/ontologic-lib/" cp examples/*.logic "${TARGET_DIR}/examples/" cp README.md LICENSE "${TARGET_DIR}/" -echo "🗜️ Archiving release tarball..." +echo "Archiving release tarball..." tar -czf "${DIST_DIR}/${PACKAGE_NAME}.tar.gz" -C "${DIST_DIR}" "${PACKAGE_NAME}" -echo "🔑 Generating SHA256 checksum..." +echo "Generating SHA256 checksum..." (cd "${DIST_DIR}" && sha256sum "${PACKAGE_NAME}.tar.gz" > "${PACKAGE_NAME}.tar.gz.sha256") -echo "✅ Release package successfully created: ${DIST_DIR}/${PACKAGE_NAME}.tar.gz" +echo "Release package successfully created: ${DIST_DIR}/${PACKAGE_NAME}.tar.gz" diff --git a/setup.sh b/setup.sh index f580aca..208b022 100755 --- a/setup.sh +++ b/setup.sh @@ -19,12 +19,12 @@ fi echo "Updating package lists..." sudo apt-get update -echo "Installing haskell-stack and docker-compose..." -sudo apt-get install -y haskell-stack docker-compose +echo "Installing haskell-stack..." +sudo apt-get install -y haskell-stack echo "Checking versions..." stack --version -docker-compose --version +if command -v docker >/dev/null; then docker compose version || true; else echo "docker not found (optional: only the neo4j test needs it)"; fi # --- SDKMAN Setup --- if [ ! -d "$HOME/.sdkman" ]; then diff --git a/site/domains.html b/site/domains.html index a300b64..43af5d5 100644 --- a/site/domains.html +++ b/site/domains.html @@ -9,7 +9,7 @@ <link rel="stylesheet" href="assets/style.css"></head><body> <a class="skip" href="#main">Skip to content</a> <header class="nav"><div class="wrap"><a class="brand" href="index.html"><svg width="22" height="22" viewBox="0 0 32 32" aria-hidden="true"><path d="M16 5l9 5v12l-9 5-9-5V10z" fill="none" stroke="#00e5ff" stroke-width="2.5"/><circle cx="16" cy="16" r="3" fill="#18a0ff"/></svg>OntoLogic</a><nav aria-label="Main"><ul><li><a href="index.html">Home</a></li><li><a href="domains.html" aria-current="page">Domains</a></li><li><a href="docs.html">Docs</a></li><li><a href="https://github.com/bsommers/OntoLogic">GitHub</a></li></ul></nav></div></header> -<main id="main"><section><div class="wrap"><h1 style="font-size:clamp(1.8rem,6vw,3rem);text-shadow:0 0 12px var(--cyan)">DOMAIN EXAMPLES</h1><p class="lede">Each card links to the <code>.logic</code> source. Diagrams are generated from the models with the D2 emitter.</p><div class="sector"><h2>Energy, Mining & Industry</h2><div class="grid"><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_mining.logic" aria-label="Mining source"><div class="thumb" id="t-domain_mining"><img src="assets/diagrams/domain_mining.svg" alt="Mining ontology diagram" loading="lazy" data-ph="Mining"></div></a><h3>Mining</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_mining.logic">domain_mining.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_energy.logic" aria-label="BFO Energy source"><div class="thumb" id="t-bfo_energy"><img src="assets/diagrams/bfo_energy.svg" alt="BFO Energy ontology diagram" loading="lazy" data-ph="BFO Energy"></div></a><h3>BFO Energy</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_energy.logic">bfo_energy.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_manufacturing.logic" aria-label="BFO Manufacturing source"><div class="thumb" id="t-bfo_manufacturing"><img src="assets/diagrams/bfo_manufacturing.svg" alt="BFO Manufacturing ontology diagram" loading="lazy" data-ph="BFO Manufacturing"></div></a><h3>BFO Manufacturing</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_manufacturing.logic">bfo_manufacturing.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/smart_factory.logic" aria-label="Smart Factory source"><div class="thumb" id="t-smart_factory"><img src="assets/diagrams/smart_factory.svg" alt="Smart Factory ontology diagram" loading="lazy" data-ph="Smart Factory"></div></a><h3>Smart Factory</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/smart_factory.logic">smart_factory.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/smart_grid_relational.logic" aria-label="Smart Grid source"><div class="thumb" id="t-smart_grid_relational"><img src="assets/diagrams/smart_grid_relational.svg" alt="Smart Grid ontology diagram" loading="lazy" data-ph="Smart Grid"></div></a><h3>Smart Grid</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/smart_grid_relational.logic">smart_grid_relational.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/car_manufacturer.logic" aria-label="Car Manufacturer source"><div class="thumb" id="t-car_manufacturer"><img src="assets/diagrams/car_manufacturer.svg" alt="Car Manufacturer ontology diagram" loading="lazy" data-ph="Car Manufacturer"></div></a><h3>Car Manufacturer</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/car_manufacturer.logic">car_manufacturer.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/dough_factory.logic" aria-label="Dough Factory source"><div class="thumb" id="t-dough_factory"><img src="assets/diagrams/dough_factory.svg" alt="Dough Factory ontology diagram" loading="lazy" data-ph="Dough Factory"></div></a><h3>Dough Factory</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/dough_factory.logic">dough_factory.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_semiconductor_fab.logic" aria-label="Semiconductor Fab source"><div class="thumb" id="t-domain_semiconductor_fab"><img src="assets/diagrams/domain_semiconductor_fab.svg" alt="Semiconductor Fab ontology diagram" loading="lazy" data-ph="Semiconductor Fab"></div></a><h3>Semiconductor Fab</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_semiconductor_fab.logic">domain_semiconductor_fab.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_ics.logic" aria-label="Industrial Control Systems source"><div class="thumb" id="t-domain_ics"><img src="assets/diagrams/domain_ics.svg" alt="Industrial Control Systems ontology diagram" loading="lazy" data-ph="Industrial Control Systems"></div></a><h3>Industrial Control Systems</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_ics.logic">domain_ics.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_iiot.logic" aria-label="Industrial IoT source"><div class="thumb" id="t-domain_iiot"><img src="assets/diagrams/domain_iiot.svg" alt="Industrial IoT ontology diagram" loading="lazy" data-ph="Industrial IoT"></div></a><h3>Industrial IoT</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_iiot.logic">domain_iiot.logic</a></p></article></div></div><div class="sector"><h2>Cloud, Security & Software</h2><div class="grid"><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_cloud_datacenter.logic" aria-label="Cloud Datacenter source"><div class="thumb" id="t-domain_cloud_datacenter"><img src="assets/diagrams/domain_cloud_datacenter.svg" alt="Cloud Datacenter ontology diagram" loading="lazy" data-ph="Cloud Datacenter"></div></a><h3>Cloud Datacenter</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_cloud_datacenter.logic">domain_cloud_datacenter.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_security_trust.logic" aria-label="Security & Trust source"><div class="thumb" id="t-domain_security_trust"><img src="assets/diagrams/domain_security_trust.svg" alt="Security & Trust ontology diagram" loading="lazy" data-ph="Security & Trust"></div></a><h3>Security & Trust</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_security_trust.logic">domain_security_trust.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_cybersecurity_soc.logic" aria-label="Cybersecurity SOC source"><div class="thumb" id="t-domain_cybersecurity_soc"><img src="assets/diagrams/domain_cybersecurity_soc.svg" alt="Cybersecurity SOC ontology diagram" loading="lazy" data-ph="Cybersecurity SOC"></div></a><h3>Cybersecurity SOC</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_cybersecurity_soc.logic">domain_cybersecurity_soc.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_software_delivery.logic" aria-label="Software Delivery source"><div class="thumb" id="t-domain_software_delivery"><img src="assets/diagrams/domain_software_delivery.svg" alt="Software Delivery ontology diagram" loading="lazy" data-ph="Software Delivery"></div></a><h3>Software Delivery</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_software_delivery.logic">domain_software_delivery.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/mqtt_operational.logic" aria-label="MQTT Operational source"><div class="thumb" id="t-mqtt_operational"><img src="assets/diagrams/mqtt_operational.svg" alt="MQTT Operational ontology diagram" loading="lazy" data-ph="MQTT Operational"></div></a><h3>MQTT Operational</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/mqtt_operational.logic">mqtt_operational.logic</a></p></article></div></div><div class="sector"><h2>IoT & Engineering</h2><div class="grid"><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_iot_smart_home.logic" aria-label="IoT Smart Home source"><div class="thumb" id="t-domain_iot_smart_home"><img src="assets/diagrams/domain_iot_smart_home.svg" alt="IoT Smart Home ontology diagram" loading="lazy" data-ph="IoT Smart Home"></div></a><h3>IoT Smart Home</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_iot_smart_home.logic">domain_iot_smart_home.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_aerospace.logic" aria-label="Aerospace source"><div class="thumb" id="t-domain_aerospace"><img src="assets/diagrams/domain_aerospace.svg" alt="Aerospace ontology diagram" loading="lazy" data-ph="Aerospace"></div></a><h3>Aerospace</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_aerospace.logic">domain_aerospace.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_systems_engineering.logic" aria-label="Systems Engineering source"><div class="thumb" id="t-domain_systems_engineering"><img src="assets/diagrams/domain_systems_engineering.svg" alt="Systems Engineering ontology diagram" loading="lazy" data-ph="Systems Engineering"></div></a><h3>Systems Engineering</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_systems_engineering.logic">domain_systems_engineering.logic</a></p></article></div></div><div class="sector"><h2>Science & Health</h2><div class="grid"><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_science_lab.logic" aria-label="Science Lab source"><div class="thumb" id="t-domain_science_lab"><img src="assets/diagrams/domain_science_lab.svg" alt="Science Lab ontology diagram" loading="lazy" data-ph="Science Lab"></div></a><h3>Science Lab</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_science_lab.logic">domain_science_lab.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_research_projects.logic" aria-label="Research Projects source"><div class="thumb" id="t-domain_research_projects"><img src="assets/diagrams/domain_research_projects.svg" alt="Research Projects ontology diagram" loading="lazy" data-ph="Research Projects"></div></a><h3>Research Projects</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_research_projects.logic">domain_research_projects.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_clinical_medicine.logic" aria-label="Clinical Medicine source"><div class="thumb" id="t-domain_clinical_medicine"><img src="assets/diagrams/domain_clinical_medicine.svg" alt="Clinical Medicine ontology diagram" loading="lazy" data-ph="Clinical Medicine"></div></a><h3>Clinical Medicine</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_clinical_medicine.logic">domain_clinical_medicine.logic</a></p></article></div></div><div class="sector"><h2>Business, Food & Logistics</h2><div class="grid"><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_customer_service.logic" aria-label="Customer Service source"><div class="thumb" id="t-domain_customer_service"><img src="assets/diagrams/domain_customer_service.svg" alt="Customer Service ontology diagram" loading="lazy" data-ph="Customer Service"></div></a><h3>Customer Service</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_customer_service.logic">domain_customer_service.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_customer_success.logic" aria-label="Customer Success source"><div class="thumb" id="t-domain_customer_success"><img src="assets/diagrams/domain_customer_success.svg" alt="Customer Success ontology diagram" loading="lazy" data-ph="Customer Success"></div></a><h3>Customer Success</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_customer_success.logic">domain_customer_success.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_food_service.logic" aria-label="Food Service source"><div class="thumb" id="t-domain_food_service"><img src="assets/diagrams/domain_food_service.svg" alt="Food Service ontology diagram" loading="lazy" data-ph="Food Service"></div></a><h3>Food Service</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_food_service.logic">domain_food_service.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_logistics.logic" aria-label="Logistics source"><div class="thumb" id="t-domain_logistics"><img src="assets/diagrams/domain_logistics.svg" alt="Logistics ontology diagram" loading="lazy" data-ph="Logistics"></div></a><h3>Logistics</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_logistics.logic">domain_logistics.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_agriculture.logic" aria-label="Agriculture source"><div class="thumb" id="t-domain_agriculture"><img src="assets/diagrams/domain_agriculture.svg" alt="Agriculture ontology diagram" loading="lazy" data-ph="Agriculture"></div></a><h3>Agriculture</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_agriculture.logic">domain_agriculture.logic</a></p></article></div></div></div></section></main><script> +<main id="main"><section><div class="wrap"><h1 style="font-size:clamp(1.8rem,6vw,3rem);text-shadow:0 0 12px var(--cyan)">DOMAIN EXAMPLES</h1><p class="lede">Each card links to the <code>.logic</code> source. Diagrams are generated from the models with the D2 emitter.</p><div class="sector"><h2>Energy, Mining & Industry</h2><div class="grid"><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_mining.logic" aria-label="Mining source"><div class="thumb" id="t-domain_mining"><img src="assets/diagrams/domain_mining.svg" alt="Mining ontology diagram" loading="lazy" data-ph="Mining"></div></a><h3>Mining</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_mining.logic">domain_mining.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_energy.logic" aria-label="BFO Energy source"><div class="thumb" id="t-bfo_energy"><img src="assets/diagrams/bfo_energy.svg" alt="BFO Energy ontology diagram" loading="lazy" data-ph="BFO Energy"></div></a><h3>BFO Energy</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_energy.logic">bfo_energy.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_manufacturing.logic" aria-label="BFO Manufacturing source"><div class="thumb" id="t-bfo_manufacturing"><img src="assets/diagrams/bfo_manufacturing.svg" alt="BFO Manufacturing ontology diagram" loading="lazy" data-ph="BFO Manufacturing"></div></a><h3>BFO Manufacturing</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_manufacturing.logic">bfo_manufacturing.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/smart_factory.logic" aria-label="Smart Factory source"><div class="thumb" id="t-smart_factory"><img src="assets/diagrams/smart_factory.svg" alt="Smart Factory ontology diagram" loading="lazy" data-ph="Smart Factory"></div></a><h3>Smart Factory</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/smart_factory.logic">smart_factory.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/smart_grid_relational.logic" aria-label="Smart Grid source"><div class="thumb" id="t-smart_grid_relational"><img src="assets/diagrams/smart_grid_relational.svg" alt="Smart Grid ontology diagram" loading="lazy" data-ph="Smart Grid"></div></a><h3>Smart Grid</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/smart_grid_relational.logic">smart_grid_relational.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/car_manufacturer.logic" aria-label="Car Manufacturer source"><div class="thumb" id="t-car_manufacturer"><img src="assets/diagrams/car_manufacturer.svg" alt="Car Manufacturer ontology diagram" loading="lazy" data-ph="Car Manufacturer"></div></a><h3>Car Manufacturer</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/car_manufacturer.logic">car_manufacturer.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/dough_factory.logic" aria-label="Dough Factory source"><div class="thumb" id="t-dough_factory"><img src="assets/diagrams/dough_factory.svg" alt="Dough Factory ontology diagram" loading="lazy" data-ph="Dough Factory"></div></a><h3>Dough Factory</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/dough_factory.logic">dough_factory.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_semiconductor_fab.logic" aria-label="Semiconductor Fab source"><div class="thumb" id="t-domain_semiconductor_fab"><img src="assets/diagrams/domain_semiconductor_fab.svg" alt="Semiconductor Fab ontology diagram" loading="lazy" data-ph="Semiconductor Fab"></div></a><h3>Semiconductor Fab</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_semiconductor_fab.logic">domain_semiconductor_fab.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_ics.logic" aria-label="Industrial Control Systems source"><div class="thumb" id="t-domain_ics"><img src="assets/diagrams/domain_ics.svg" alt="Industrial Control Systems ontology diagram" loading="lazy" data-ph="Industrial Control Systems"></div></a><h3>Industrial Control Systems</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_ics.logic">domain_ics.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_iiot.logic" aria-label="Industrial IoT source"><div class="thumb" id="t-domain_iiot"><img src="assets/diagrams/domain_iiot.svg" alt="Industrial IoT ontology diagram" loading="lazy" data-ph="Industrial IoT"></div></a><h3>Industrial IoT</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_iiot.logic">domain_iiot.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_morphisms_plant.logic" aria-label="BFO Morphisms Plant source"><div class="thumb" id="t-bfo_morphisms_plant"><img src="assets/diagrams/bfo_morphisms_plant.svg" alt="BFO Morphisms Plant ontology diagram" loading="lazy" data-ph="BFO Morphisms Plant"></div></a><h3>BFO Morphisms Plant</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_morphisms_plant.logic">bfo_morphisms_plant.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_unified.logic" aria-label="BFO Unified source"><div class="thumb" id="t-bfo_unified"><img src="assets/diagrams/bfo_unified.svg" alt="BFO Unified ontology diagram" loading="lazy" data-ph="BFO Unified"></div></a><h3>BFO Unified</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/bfo_unified.logic">bfo_unified.logic</a></p></article></div></div><div class="sector"><h2>Cloud, Security & Software</h2><div class="grid"><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_cloud_datacenter.logic" aria-label="Cloud Datacenter source"><div class="thumb" id="t-domain_cloud_datacenter"><img src="assets/diagrams/domain_cloud_datacenter.svg" alt="Cloud Datacenter ontology diagram" loading="lazy" data-ph="Cloud Datacenter"></div></a><h3>Cloud Datacenter</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_cloud_datacenter.logic">domain_cloud_datacenter.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_security_trust.logic" aria-label="Security & Trust source"><div class="thumb" id="t-domain_security_trust"><img src="assets/diagrams/domain_security_trust.svg" alt="Security & Trust ontology diagram" loading="lazy" data-ph="Security & Trust"></div></a><h3>Security & Trust</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_security_trust.logic">domain_security_trust.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/security_policy.logic" aria-label="Security Policy source"><div class="thumb" id="t-security_policy"><img src="assets/diagrams/security_policy.svg" alt="Security Policy ontology diagram" loading="lazy" data-ph="Security Policy"></div></a><h3>Security Policy</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/security_policy.logic">security_policy.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_cybersecurity_soc.logic" aria-label="Cybersecurity SOC source"><div class="thumb" id="t-domain_cybersecurity_soc"><img src="assets/diagrams/domain_cybersecurity_soc.svg" alt="Cybersecurity SOC ontology diagram" loading="lazy" data-ph="Cybersecurity SOC"></div></a><h3>Cybersecurity SOC</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_cybersecurity_soc.logic">domain_cybersecurity_soc.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_software_delivery.logic" aria-label="Software Delivery source"><div class="thumb" id="t-domain_software_delivery"><img src="assets/diagrams/domain_software_delivery.svg" alt="Software Delivery ontology diagram" loading="lazy" data-ph="Software Delivery"></div></a><h3>Software Delivery</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_software_delivery.logic">domain_software_delivery.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/mqtt_operational.logic" aria-label="MQTT Operational source"><div class="thumb" id="t-mqtt_operational"><img src="assets/diagrams/mqtt_operational.svg" alt="MQTT Operational ontology diagram" loading="lazy" data-ph="MQTT Operational"></div></a><h3>MQTT Operational</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/mqtt_operational.logic">mqtt_operational.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/mqtt_ecosystem_unified.logic" aria-label="MQTT Ecosystem Unified source"><div class="thumb" id="t-mqtt_ecosystem_unified"><img src="assets/diagrams/mqtt_ecosystem_unified.svg" alt="MQTT Ecosystem Unified ontology diagram" loading="lazy" data-ph="MQTT Ecosystem Unified"></div></a><h3>MQTT Ecosystem Unified</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/mqtt_ecosystem_unified.logic">mqtt_ecosystem_unified.logic</a></p></article></div></div><div class="sector"><h2>IoT & Engineering</h2><div class="grid"><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_iot_smart_home.logic" aria-label="IoT Smart Home source"><div class="thumb" id="t-domain_iot_smart_home"><img src="assets/diagrams/domain_iot_smart_home.svg" alt="IoT Smart Home ontology diagram" loading="lazy" data-ph="IoT Smart Home"></div></a><h3>IoT Smart Home</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_iot_smart_home.logic">domain_iot_smart_home.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_aerospace.logic" aria-label="Aerospace source"><div class="thumb" id="t-domain_aerospace"><img src="assets/diagrams/domain_aerospace.svg" alt="Aerospace ontology diagram" loading="lazy" data-ph="Aerospace"></div></a><h3>Aerospace</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_aerospace.logic">domain_aerospace.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_systems_engineering.logic" aria-label="Systems Engineering source"><div class="thumb" id="t-domain_systems_engineering"><img src="assets/diagrams/domain_systems_engineering.svg" alt="Systems Engineering ontology diagram" loading="lazy" data-ph="Systems Engineering"></div></a><h3>Systems Engineering</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_systems_engineering.logic">domain_systems_engineering.logic</a></p></article></div></div><div class="sector"><h2>Science & Health</h2><div class="grid"><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_science_lab.logic" aria-label="Science Lab source"><div class="thumb" id="t-domain_science_lab"><img src="assets/diagrams/domain_science_lab.svg" alt="Science Lab ontology diagram" loading="lazy" data-ph="Science Lab"></div></a><h3>Science Lab</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_science_lab.logic">domain_science_lab.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_research_projects.logic" aria-label="Research Projects source"><div class="thumb" id="t-domain_research_projects"><img src="assets/diagrams/domain_research_projects.svg" alt="Research Projects ontology diagram" loading="lazy" data-ph="Research Projects"></div></a><h3>Research Projects</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_research_projects.logic">domain_research_projects.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_clinical_medicine.logic" aria-label="Clinical Medicine source"><div class="thumb" id="t-domain_clinical_medicine"><img src="assets/diagrams/domain_clinical_medicine.svg" alt="Clinical Medicine ontology diagram" loading="lazy" data-ph="Clinical Medicine"></div></a><h3>Clinical Medicine</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_clinical_medicine.logic">domain_clinical_medicine.logic</a></p></article></div></div><div class="sector"><h2>Business, Food & Logistics</h2><div class="grid"><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_customer_service.logic" aria-label="Customer Service source"><div class="thumb" id="t-domain_customer_service"><img src="assets/diagrams/domain_customer_service.svg" alt="Customer Service ontology diagram" loading="lazy" data-ph="Customer Service"></div></a><h3>Customer Service</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_customer_service.logic">domain_customer_service.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_customer_success.logic" aria-label="Customer Success source"><div class="thumb" id="t-domain_customer_success"><img src="assets/diagrams/domain_customer_success.svg" alt="Customer Success ontology diagram" loading="lazy" data-ph="Customer Success"></div></a><h3>Customer Success</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_customer_success.logic">domain_customer_success.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_food_service.logic" aria-label="Food Service source"><div class="thumb" id="t-domain_food_service"><img src="assets/diagrams/domain_food_service.svg" alt="Food Service ontology diagram" loading="lazy" data-ph="Food Service"></div></a><h3>Food Service</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_food_service.logic">domain_food_service.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_logistics.logic" aria-label="Logistics source"><div class="thumb" id="t-domain_logistics"><img src="assets/diagrams/domain_logistics.svg" alt="Logistics ontology diagram" loading="lazy" data-ph="Logistics"></div></a><h3>Logistics</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_logistics.logic">domain_logistics.logic</a></p></article><article class="card"><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_agriculture.logic" aria-label="Agriculture source"><div class="thumb" id="t-domain_agriculture"><img src="assets/diagrams/domain_agriculture.svg" alt="Agriculture ontology diagram" loading="lazy" data-ph="Agriculture"></div></a><h3>Agriculture</h3><p><a href="https://github.com/bsommers/OntoLogic/blob/main/examples/domain_agriculture.logic">domain_agriculture.logic</a></p></article></div></div></div></section></main><script> document.querySelectorAll('.thumb img').forEach(function(i){i.addEventListener('error',function(){var d=i.parentNode;d.classList.add('ph');d.textContent=i.getAttribute('data-ph')+' diagram pending';});}); </script> <footer><div class="wrap"><span>OntoLogic — Logic-as-Code. Licensed under <a href="https://github.com/bsommers/OntoLogic/blob/main/LICENSE">Apache-2.0</a>.</span><span><a href="https://github.com/bsommers/OntoLogic">Source on GitHub</a> · <a href="https://github.com/bsommers/OntoLogic/blob/main/CHANGELOG.md">Changelog</a></span></div></footer></body></html> diff --git a/src/Emitters/Go.hs b/src/Emitters/Go.hs index e8968b4..5637b95 100644 --- a/src/Emitters/Go.hs +++ b/src/Emitters/Go.hs @@ -16,10 +16,10 @@ emitGo reg = in "// Code generated by OntoLogic. DO NOT EDIT.\n" ++ "package models\n\n" ++ (if usesFmt then "import \"fmt\"\n\n" else "") ++ - concatMap emitGoStruct classes + concatMap (emitGoStruct classes) classes -emitGoStruct :: CompiledClass -> String -emitGoStruct cls = +emitGoStruct :: [CompiledClass] -> CompiledClass -> String +emitGoStruct classes cls = let cName = sanitizeIdent (compClassName cls) parent = compParentClass cls directProps = filter (not . compIsInherited) (compProperties cls) @@ -28,7 +28,7 @@ emitGoStruct cls = maybe "" (\p -> " " ++ sanitizeIdent p ++ "\n") parent ++ concatMap emitGoField directProps ++ "}\n\n" - validateImpl = emitGoValidation cls + validateImpl = emitGoValidation classes cls in structDef ++ validateImpl emitGoField :: CompiledProperty -> String @@ -43,8 +43,8 @@ emitGoField p = jsonTag = compPropName p in " " ++ fName ++ " " ++ fType ++ " `json:\"" ++ jsonTag ++ ",omitempty\"`\n" -emitGoValidation :: CompiledClass -> String -emitGoValidation cls = +emitGoValidation :: [CompiledClass] -> CompiledClass -> String +emitGoValidation classes cls = let cName = sanitizeIdent (compClassName cls) parent = compParentClass cls recv = "m" @@ -53,7 +53,7 @@ emitGoValidation cls = Nothing -> "" allPropsWithConstraints = filter (not . null . compConstraints) (compProperties cls) propChecks = concatMap (emitGoPropValidation recv) allPropsWithConstraints - condChecks = concatMap (emitGoConditionalValidation recv) (compConditionalAxioms cls) + condChecks = concatMap (emitGoConditionalValidation recv (isOptional classes cls)) (compEnforced cls) in "func (" ++ recv ++ " *" ++ cName ++ ") Validate() []string {\n" ++ " var allErrors []string\n" ++ parentCheck ++ @@ -135,35 +135,44 @@ toPascalCase raw = capitalize [] = [] capitalize (c:cs) = toUpper c : cs -emitGoConditionalValidation :: String -> ConditionalConstraint -> String -emitGoConditionalValidation recv ax = - " if (" ++ emitGoExpr recv (condPremise ax) ++ ") && !(" ++ emitGoExpr recv (condConclusion ax) ++ ") {\n" ++ +-- | Optional scalars are pointers in the generated struct. A property may be declared on an +-- ancestor; Go promotes the embedded struct's fields, so only its cardinality matters. +isOptional :: [CompiledClass] -> CompiledClass -> Name -> Bool +isOptional classes cls prop = case findDeclaredProperty classes cls prop of + Just (_, _, p) -> compCardinality p == CardZeroOrOne + Nothing -> False + +emitGoConditionalValidation :: String -> (Name -> Bool) -> ConditionalConstraint -> String +emitGoConditionalValidation recv opt ax = + " if " ++ guardExpr ++ " {\n" ++ " allErrors = append(allErrors, \"Axiom violation: " ++ escapeGo (condDescription ax) ++ "\")\n" ++ " }\n" - -emitGoExpr :: String -> FOL -> String -emitGoExpr recv (Predicate op args) - | op `elem` ["eq", "ne", "gt", "gte", "lt", "lte"] = - case args of - [Var prop, Constant val] -> emitGoBinary recv op prop val - [Constant val, Var prop] -> emitGoBinary recv (invertCompOp op) prop val - _ -> "true" - | otherwise = - case args of - (Var prop:_) -> "(" ++ recv ++ "." ++ toPascalCase prop ++ " == true)" - [] -> "(" ++ recv ++ "." ++ toPascalCase op ++ " == true)" - _ -> "true" -emitGoExpr recv (And p1 p2) = "(" ++ emitGoExpr recv p1 ++ " && " ++ emitGoExpr recv p2 ++ ")" -emitGoExpr recv (Or p1 p2) = "(" ++ emitGoExpr recv p1 ++ " || " ++ emitGoExpr recv p2 ++ ")" -emitGoExpr recv (Not p) = "!(" ++ emitGoExpr recv p ++ ")" -emitGoExpr _ _ = "true" - -emitGoBinary :: String -> String -> Name -> String -> String -emitGoBinary recv op prop val = - let fld = recv ++ "." ++ toPascalCase prop + where + guardExpr = case condPremise ax of + Top -> "!(" ++ emitGoExpr recv opt (condConclusion ax) ++ ")" + pre -> "(" ++ emitGoExpr recv opt pre ++ ") && !(" ++ emitGoExpr recv opt (condConclusion ax) ++ ")" + +-- | Total on what 'IR.normalizeCondition' produces; anything else was kept out upstream and +-- fails loudly here instead of becoming a check that cannot fail. +emitGoExpr :: String -> (Name -> Bool) -> FOL -> String +emitGoExpr recv opt (Predicate op [Var prop, Constant val]) | op `elem` comparisonOps = emitGoBinary recv (opt prop) op prop val +emitGoExpr recv opt (Predicate flag []) = emitGoBinary recv (opt flag) "eq" flag "True" +emitGoExpr recv opt (And p1 p2) = "(" ++ emitGoExpr recv opt p1 ++ " && " ++ emitGoExpr recv opt p2 ++ ")" +emitGoExpr recv opt (Or p1 p2) = "(" ++ emitGoExpr recv opt p1 ++ " || " ++ emitGoExpr recv opt p2 ++ ")" +emitGoExpr recv opt (Not p) = "!(" ++ emitGoExpr recv opt p ++ ")" +emitGoExpr _ _ Top = "true" +emitGoExpr _ _ Bottom = "false" +emitGoExpr _ _ other = error ("Go emitter: untranslatable conditional " ++ formatFOL other) + +emitGoBinary :: String -> Bool -> String -> Name -> String -> String +emitGoBinary recv optional op prop val = + let field = recv ++ "." ++ toPascalCase prop + fld = if optional then "*" ++ field else field valExpr = case val of "True" -> "true" "False" -> "false" + "true" -> "true" + "false" -> "false" v | isNumber v -> v v -> "\"" ++ escapeGo v ++ "\"" goOp = case op of @@ -173,15 +182,11 @@ emitGoBinary recv op prop val = "gte" -> ">=" "lt" -> "<" "lte" -> "<=" - _ -> "==" - in "(" ++ fld ++ " " ++ goOp ++ " " ++ valExpr ++ ")" - -invertCompOp :: String -> String -invertCompOp "gt" = "lt" -invertCompOp "gte" = "lte" -invertCompOp "lt" = "gt" -invertCompOp "lte" = "gte" -invertCompOp op = op + _ -> error ("Go emitter: unknown comparison " ++ op) + cmp = fld ++ " " ++ goOp ++ " " ++ valExpr + in if not optional then "(" ++ cmp ++ ")" + else if op == "ne" then "(" ++ field ++ " == nil || " ++ cmp ++ ")" + else "(" ++ field ++ " != nil && " ++ cmp ++ ")" escapeGo :: String -> String escapeGo = escapeTargetString diff --git a/src/Emitters/Java.hs b/src/Emitters/Java.hs index e2233c2..c1e2f1c 100644 --- a/src/Emitters/Java.hs +++ b/src/Emitters/Java.hs @@ -17,43 +17,48 @@ emitJavaClass :: String -> CompiledClass -> String emitJavaClass pkg cls = "package " ++ pkg ++ ";\n" ++ "import jakarta.validation.constraints.*;\n" ++ - (if null (compConditionalAxioms cls) then "" else "import java.util.Objects;\n") ++ + (if null (compEnforced cls) then "" else "import java.util.Objects;\n") ++ "\n" ++ "public class " ++ sanitizeIdent (compClassName cls) ++ maybe "" (\p -> " extends " ++ sanitizeIdent p) (compParentClass cls) ++ " {\n" ++ concatMap (emitFieldOrGetter (compClassName cls)) (compProperties cls) ++ - concatMap emitJavaConditionalConstraint (zip [1..] (compConditionalAxioms cls)) ++ + concatMap (emitJavaConditionalConstraint (compClassName cls)) (zip [1..] (compEnforced cls)) ++ "}\n" -emitJavaConditionalConstraint :: (Int, ConditionalConstraint) -> String -emitJavaConditionalConstraint (idx, ax) = +-- | The method name carries the class name: a subclass that reused "isValidConstraint1" would +-- override the inherited method and the parent's conditionals would stop being checked. +emitJavaConditionalConstraint :: Name -> (Int, ConditionalConstraint) -> String +emitJavaConditionalConstraint cName (idx, ax) = " @AssertTrue(message = \"Constraint failed: " ++ escapeJava (condDescription ax) ++ "\")\n" ++ - " public boolean isValidConstraint" ++ show idx ++ "() {\n" ++ - " if (" ++ emitJavaExpr (condPremise ax) ++ ") {\n" ++ - " return " ++ emitJavaExpr (condConclusion ax) ++ ";\n" ++ - " }\n" ++ - " return true;\n" ++ + " public boolean isValidConstraint_" ++ sanitizeIdent cName ++ "_" ++ show idx ++ "() {\n" ++ + (case condPremise ax of + Top -> " return " ++ emitJavaExpr (condConclusion ax) ++ ";\n" + pre -> " if (" ++ emitJavaExpr pre ++ ") {\n" ++ + " return " ++ emitJavaExpr (condConclusion ax) ++ ";\n" ++ + " }\n" ++ + " return true;\n") ++ " }\n\n" +-- | Total on what 'IR.normalizeCondition' produces; anything else was kept out upstream and +-- fails loudly here instead of becoming a check that cannot fail. Fields are read through +-- their getters: a property declared on an ancestor is private to the ancestor. emitJavaExpr :: FOL -> String -emitJavaExpr (Predicate op args) - | op `elem` ["eq", "ne", "gt", "gte", "lt", "lte"] = - case args of - [Var prop, Constant val] -> emitJavaBinary op prop val - [Constant val, Var prop] -> emitJavaBinary (invertCompOp op) prop val - _ -> "true" - | otherwise = - case args of - (Var prop:_) -> "(\"True\".equalsIgnoreCase(String.valueOf(this." ++ sanitizeIdent prop ++ ")) || Boolean.TRUE.equals(this." ++ sanitizeIdent prop ++ "))" - [] -> "(\"True\".equalsIgnoreCase(String.valueOf(this." ++ sanitizeIdent op ++ ")) || Boolean.TRUE.equals(this." ++ sanitizeIdent op ++ "))" - _ -> "true" +emitJavaExpr (Predicate op [Var prop, Constant val]) | op `elem` comparisonOps = emitJavaBinary op prop val +emitJavaExpr (Predicate flag []) = + let fld = javaGetter flag + in "(\"True\".equalsIgnoreCase(String.valueOf(" ++ fld ++ ")) || Boolean.TRUE.equals(" ++ fld ++ "))" emitJavaExpr (And p1 p2) = "(" ++ emitJavaExpr p1 ++ " && " ++ emitJavaExpr p2 ++ ")" emitJavaExpr (Or p1 p2) = "(" ++ emitJavaExpr p1 ++ " || " ++ emitJavaExpr p2 ++ ")" emitJavaExpr (Not p) = "!(" ++ emitJavaExpr p ++ ")" -emitJavaExpr _ = "true" +emitJavaExpr Top = "true" +emitJavaExpr Bottom = "false" +emitJavaExpr other = error ("Java emitter: untranslatable conditional " ++ formatFOL other) + +javaGetter :: Name -> String +javaGetter prop = "this.get" ++ capitalize (sanitizeIdent prop) ++ "()" emitJavaBinary :: String -> Name -> String -> String emitJavaBinary op prop val = - let fld = "this." ++ sanitizeIdent prop + let fld = javaGetter prop in case op of "eq" | val `elem` ["True", "true"] -> "(\"True\".equalsIgnoreCase(String.valueOf(" ++ fld ++ ")) || Boolean.TRUE.equals(" ++ fld ++ "))" | val `elem` ["False", "false"] -> "(\"False\".equalsIgnoreCase(String.valueOf(" ++ fld ++ ")) || Boolean.FALSE.equals(" ++ fld ++ "))" @@ -67,14 +72,7 @@ emitJavaBinary op prop val = "gte" -> "(" ++ fld ++ " != null && " ++ fld ++ " >= " ++ val ++ ")" "lt" -> "(" ++ fld ++ " != null && " ++ fld ++ " < " ++ val ++ ")" "lte" -> "(" ++ fld ++ " != null && " ++ fld ++ " <= " ++ val ++ ")" - _ -> "true" - -invertCompOp :: String -> String -invertCompOp "gt" = "lt" -invertCompOp "gte" = "lte" -invertCompOp "lt" = "gt" -invertCompOp "lte" = "gte" -invertCompOp op = op + _ -> error ("Java emitter: unknown comparison " ++ op) escapeJava :: String -> String escapeJava = escapeTargetString diff --git a/src/Emitters/Python.hs b/src/Emitters/Python.hs index ea34b24..bb600d8 100644 --- a/src/Emitters/Python.hs +++ b/src/Emitters/Python.hs @@ -9,7 +9,7 @@ emitPython :: Registry -> String emitPython reg = let modelIR = compileRegistry reg classes = irClasses modelIR - hasConditional = any (not . null . compConditionalAxioms) classes + hasConditional = any (not . null . compEnforced) classes pydanticImport = if hasConditional then "from pydantic import BaseModel, Field, model_validator\n" else "from pydantic import BaseModel, Field\n" @@ -33,40 +33,42 @@ emitPython reg = emitPythonClass :: CompiledClass -> String emitPythonClass cls = "class " ++ sanitizeIdent (compClassName cls) ++ "(" ++ maybe "BaseModel" sanitizeIdent (compParentClass cls) ++ "):\n" ++ - (if null (compProperties cls) && null (compConditionalAxioms cls) + (if null (compProperties cls) && null (compEnforced cls) then " pass\n\n" else concatMap emitFieldWithConstraints (compProperties cls) ++ - emitPythonConditionalValidators (compConditionalAxioms cls) ++ "\n") + emitPythonConditionalValidators (compClassName cls) (compEnforced cls) ++ "\n") -emitPythonConditionalValidators :: [ConditionalConstraint] -> String -emitPythonConditionalValidators [] = "" -emitPythonConditionalValidators axs = +-- | The method name carries the class name: a subclass that reused one name would replace the +-- inherited validator and silently stop enforcing the parent's conditionals. +emitPythonConditionalValidators :: Name -> [ConditionalConstraint] -> String +emitPythonConditionalValidators _ [] = "" +emitPythonConditionalValidators cName axs = "\n @model_validator(mode=\"after\")\n" ++ - " def validate_conditional_constraints(self):\n" ++ + " def validate_conditional_constraints_" ++ sanitizeIdent cName ++ "(self):\n" ++ concatMap emitSingleValidator axs ++ " return self\n" emitSingleValidator :: ConditionalConstraint -> String emitSingleValidator ax = - " if " ++ emitPythonExpr (condPremise ax) ++ " and not (" ++ emitPythonExpr (condConclusion ax) ++ "):\n" ++ + " if " ++ guardExpr ++ ":\n" ++ " raise ValueError(\"Constraint failed: " ++ escapePy (condDescription ax) ++ "\")\n" + where + guardExpr = case condPremise ax of + Top -> "not (" ++ emitPythonExpr (condConclusion ax) ++ ")" + pre -> emitPythonExpr pre ++ " and not (" ++ emitPythonExpr (condConclusion ax) ++ ")" +-- | Total on what 'IR.normalizeCondition' produces. Anything else was kept out of the +-- conditional list upstream; reaching it here is a bug, so it fails loudly instead of +-- becoming a check that cannot fail. emitPythonExpr :: FOL -> String -emitPythonExpr (Predicate op args) - | op `elem` ["eq", "ne", "gt", "gte", "lt", "lte"] = - case args of - [Var prop, Constant val] -> emitPythonBinary op prop val - [Constant val, Var prop] -> emitPythonBinary (invertCompOp op) prop val - _ -> "True" - | otherwise = - case args of - (Var prop:_) -> "(str(getattr(self, '" ++ sanitizeIdent prop ++ "', None)).lower() == 'true')" - [] -> "(str(getattr(self, '" ++ sanitizeIdent op ++ "', None)).lower() == 'true')" - _ -> "True" +emitPythonExpr (Predicate op [Var prop, Constant val]) | op `elem` comparisonOps = emitPythonBinary op prop val +emitPythonExpr (Predicate flag []) = "(str(getattr(self, '" ++ sanitizeIdent flag ++ "', None)).lower() == 'true')" emitPythonExpr (And p1 p2) = "(" ++ emitPythonExpr p1 ++ " and " ++ emitPythonExpr p2 ++ ")" emitPythonExpr (Or p1 p2) = "(" ++ emitPythonExpr p1 ++ " or " ++ emitPythonExpr p2 ++ ")" emitPythonExpr (Not p) = "not (" ++ emitPythonExpr p ++ ")" -emitPythonExpr _ = "True" +emitPythonExpr Top = "True" +emitPythonExpr Bottom = "False" +emitPythonExpr other = error ("Python emitter: untranslatable conditional " ++ formatFOL other) emitPythonBinary :: String -> Name -> String -> String emitPythonBinary op prop val = @@ -84,14 +86,7 @@ emitPythonBinary op prop val = "gte" -> "(" ++ fld ++ " is not None and " ++ fld ++ " >= " ++ val ++ ")" "lt" -> "(" ++ fld ++ " is not None and " ++ fld ++ " < " ++ val ++ ")" "lte" -> "(" ++ fld ++ " is not None and " ++ fld ++ " <= " ++ val ++ ")" - _ -> "True" - -invertCompOp :: String -> String -invertCompOp "gt" = "lt" -invertCompOp "gte" = "lte" -invertCompOp "lt" = "gt" -invertCompOp "lte" = "gte" -invertCompOp op = op + _ -> error ("Python emitter: unknown comparison " ++ op) escapePy :: String -> String escapePy = escapeTargetString diff --git a/src/Emitters/Rust.hs b/src/Emitters/Rust.hs index a099def..ac2470d 100644 --- a/src/Emitters/Rust.hs +++ b/src/Emitters/Rust.hs @@ -12,10 +12,10 @@ emitRust reg = classes = irClasses modelIR parents = [ (compClassName c, compParentClass c) | c <- classes ] in "// Generated by OntoLogic - Rust Model Target\n\n" ++ - concatMap (emitRustStruct parents) classes + concatMap (emitRustStruct parents classes) classes -emitRustStruct :: [(Name, Maybe Name)] -> CompiledClass -> String -emitRustStruct parents cls = +emitRustStruct :: [(Name, Maybe Name)] -> [CompiledClass] -> CompiledClass -> String +emitRustStruct parents classes cls = let cName = sanitizeIdent (compClassName cls) parent = compParentClass cls directProps = filter (not . compIsInherited) (compProperties cls) @@ -25,7 +25,7 @@ emitRustStruct parents cls = maybe "" (\p -> " pub base: " ++ sanitizeIdent p ++ ",\n") parent ++ concatMap emitRustField directProps ++ "}\n\n" - validateImpl = emitRustValidation parents cls + validateImpl = emitRustValidation parents classes cls in structDef ++ validateImpl -- | "self." plus one "base." per inheritance level between cls and the class that @@ -54,8 +54,8 @@ emitRustField p = _ -> baseType in " pub " ++ fName ++ ": " ++ fType ++ ",\n" -emitRustValidation :: [(Name, Maybe Name)] -> CompiledClass -> String -emitRustValidation parents cls = +emitRustValidation :: [(Name, Maybe Name)] -> [CompiledClass] -> CompiledClass -> String +emitRustValidation parents classes cls = let cName = sanitizeIdent (compClassName cls) parent = compParentClass cls parentCheck = case parent of @@ -63,7 +63,7 @@ emitRustValidation parents cls = Nothing -> "" allPropsWithConstraints = filter (not . null . compConstraints) (compProperties cls) propChecks = concatMap (emitPropValidation parents (compClassName cls)) allPropsWithConstraints - condChecks = concatMap (emitRustConditionalValidation parents cls) (compConditionalAxioms cls) + condChecks = concatMap (emitRustConditionalValidation classes cls) (compEnforced cls) -- `mut` on a vec nothing pushes to is an unused_mut warning in the generated crate. mutKeyword = if null parentCheck && null propChecks && null condChecks then "" else "mut " in "impl " ++ cName ++ " {\n" ++ @@ -151,48 +151,41 @@ toRustFieldName name = "box" -> "r#box" other -> other -emitRustConditionalValidation :: [(Name, Maybe Name)] -> CompiledClass -> ConditionalConstraint -> String -emitRustConditionalValidation parents cls ax = - " if (" ++ emitRustExpr parents cls (condPremise ax) ++ ") && !(" ++ emitRustExpr parents cls (condConclusion ax) ++ ") {\n" ++ +emitRustConditionalValidation :: [CompiledClass] -> CompiledClass -> ConditionalConstraint -> String +emitRustConditionalValidation classes cls ax = + " if " ++ guardExpr ++ " {\n" ++ " errors.push(\"Axiom violation: " ++ escapeRust (condDescription ax) ++ "\".to_string());\n" ++ " }\n" - -emitRustExpr :: [(Name, Maybe Name)] -> CompiledClass -> FOL -> String -emitRustExpr parents cls (Predicate op args) - | op `elem` ["eq", "ne", "gt", "gte", "lt", "lte"] = - case args of - [Var prop, Constant val] -> emitRustBinary parents cls op prop val - [Constant val, Var prop] -> emitRustBinary parents cls (invertCompOp op) prop val - _ -> "true" - | otherwise = - case args of - (Var prop:_) -> "(" ++ resolveRustAccessor parents cls prop ++ " == true)" - [] -> "(" ++ resolveRustAccessor parents cls op ++ " == true)" - _ -> "true" -emitRustExpr parents cls (And p1 p2) = "(" ++ emitRustExpr parents cls p1 ++ " && " ++ emitRustExpr parents cls p2 ++ ")" -emitRustExpr parents cls (Or p1 p2) = "(" ++ emitRustExpr parents cls p1 ++ " || " ++ emitRustExpr parents cls p2 ++ ")" -emitRustExpr parents cls (Not p) = "!(" ++ emitRustExpr parents cls p ++ ")" -emitRustExpr _ _ _ = "true" - -resolveRustAccessor :: [(Name, Maybe Name)] -> CompiledClass -> Name -> String -resolveRustAccessor parents cls prop = - case [ p | p <- compProperties cls, compPropName p == prop ] of - (p:_) -> fieldAccessor parents (compClassName cls) p - [] -> "self." ++ toRustFieldName prop - -resolveRustPropType :: CompiledClass -> Name -> Maybe PropertyType -resolveRustPropType cls prop = - case [ compPropType p | p <- compProperties cls, compPropName p == prop ] of - (t:_) -> Just t - [] -> Nothing - -emitRustBinary :: [(Name, Maybe Name)] -> CompiledClass -> String -> Name -> String -> String -emitRustBinary parents cls op prop val = - let fld = resolveRustAccessor parents cls prop - mType = resolveRustPropType cls prop + where + guardExpr = case condPremise ax of + Top -> "!(" ++ emitRustExpr classes cls (condConclusion ax) ++ ")" + pre -> "(" ++ emitRustExpr classes cls pre ++ ") && !(" ++ emitRustExpr classes cls (condConclusion ax) ++ ")" + +-- | Total on what 'IR.normalizeCondition' produces; anything else was kept out upstream and +-- fails loudly here instead of becoming a check that cannot fail. +emitRustExpr :: [CompiledClass] -> CompiledClass -> FOL -> String +emitRustExpr classes cls (Predicate op [Var prop, Constant val]) | op `elem` comparisonOps = emitRustBinary classes cls op prop val +emitRustExpr classes cls (Predicate flag []) = emitRustBinary classes cls "eq" flag "True" +emitRustExpr classes cls (And p1 p2) = "(" ++ emitRustExpr classes cls p1 ++ " && " ++ emitRustExpr classes cls p2 ++ ")" +emitRustExpr classes cls (Or p1 p2) = "(" ++ emitRustExpr classes cls p1 ++ " || " ++ emitRustExpr classes cls p2 ++ ")" +emitRustExpr classes cls (Not p) = "!(" ++ emitRustExpr classes cls p ++ ")" +emitRustExpr _ _ Top = "true" +emitRustExpr _ _ Bottom = "false" +emitRustExpr _ _ other = error ("Rust emitter: untranslatable conditional " ++ formatFOL other) + +-- | The comparison of a property with a constant. The property may live on an ancestor +-- (reached through @base@ once per inheritance step) and may be an Option. +emitRustBinary :: [CompiledClass] -> CompiledClass -> String -> Name -> String -> String +emitRustBinary classes cls op prop val = + let (path, mType, optional) = case findDeclaredProperty classes cls prop of + Just (_, depth, p) -> ( "self." ++ concat (replicate depth "base.") ++ toRustFieldName prop + , Just (compPropType p), compCardinality p == CardZeroOrOne ) + Nothing -> error ("Rust emitter: undeclared property in conditional: " ++ prop) valExpr = case val of "True" -> "true" "False" -> "false" + "true" -> "true" + "false" -> "false" v | isNumber v -> case mType of Just PTFloat -> if '.' `elem` v then v else v ++ ".0" @@ -206,15 +199,10 @@ emitRustBinary parents cls op prop val = "gte" -> ">=" "lt" -> "<" "lte" -> "<=" - _ -> "==" - in "(" ++ fld ++ " " ++ rustOp ++ " " ++ valExpr ++ ")" - -invertCompOp :: String -> String -invertCompOp "gt" = "lt" -invertCompOp "gte" = "lte" -invertCompOp "lt" = "gt" -invertCompOp "lte" = "gte" -invertCompOp op = op + _ -> error ("Rust emitter: unknown comparison " ++ op) + in if optional + then "(" ++ path ++ ".as_ref().map_or(" ++ (if op == "ne" then "true" else "false") ++ ", |v| *v " ++ rustOp ++ " " ++ valExpr ++ "))" + else "(" ++ path ++ " " ++ rustOp ++ " " ++ valExpr ++ ")" escapeRust :: String -> String escapeRust = escapeTargetString diff --git a/src/Emitters/SMT.hs b/src/Emitters/SMT.hs index 3713c32..03b1176 100644 --- a/src/Emitters/SMT.hs +++ b/src/Emitters/SMT.hs @@ -2,6 +2,7 @@ module Emitters.SMT ( emitSMT , emitSMTDeclarations , emitSMTDeclarationsNamed + , emitSMTDeclarationsUnbounded , emitPropertyFunction , smtNumeral , mapSmtType @@ -24,8 +25,19 @@ emitSMT reg = "(get-model)\n" -- | Sort, concept constants, hierarchy, property bounds and relation facts (no set-logic, no check-sat). +-- This is the standalone specification target: the bounds are asserted on the concept constant. emitSMTDeclarations :: Registry -> String -emitSMTDeclarations reg = +emitSMTDeclarations = declarations True + +-- | The same declarations without the property bound assertions. The solver checks use this: +-- a bound asserted on the concept constant holds for one fictitious entity whether or not the +-- source states it for every instance, so it can turn an empty concept into a global +-- contradiction. The real bounds reach the solver through the axioms of the first-order theory. +emitSMTDeclarationsUnbounded :: Registry -> String +emitSMTDeclarationsUnbounded = declarations False + +declarations :: Bool -> Registry -> String +declarations withBounds reg = let modelIR = compileRegistry reg classes = irClasses modelIR in "; Sort declarations\n" ++ @@ -35,8 +47,8 @@ emitSMTDeclarations reg = "; Subclass Hierarchy\n" ++ "(declare-fun subClassOf (Entity Entity) Bool)\n" ++ concatMap emitHierarchy classes ++ "\n" ++ - "; Property Functions and Bound Assertions\n" ++ - concatMap emitClassProperties classes ++ "\n" ++ + "; Property Functions" ++ (if withBounds then " and Bound Assertions" else "") ++ "\n" ++ + concatMap (emitClassProperties withBounds) classes ++ "\n" ++ "; Relational Declarations\n" ++ emitRelations (irRelations modelIR) ++ "\n" @@ -50,16 +62,19 @@ emitHierarchy cls = Just p -> "(assert (subClassOf " ++ sanitizeIdent (compClassName cls) ++ " " ++ sanitizeIdent p ++ "))\n" Nothing -> "" -emitClassProperties :: CompiledClass -> String -emitClassProperties cls = - concatMap (emitPropertyFunction (sanitizeIdent (compClassName cls))) (compProperties cls) +emitClassProperties :: Bool -> CompiledClass -> String +emitClassProperties withBounds cls = + concatMap (emitProperty withBounds (sanitizeIdent (compClassName cls))) (compProperties cls) emitPropertyFunction :: String -> CompiledProperty -> String -emitPropertyFunction cName p = +emitPropertyFunction = emitProperty True + +emitProperty :: Bool -> String -> CompiledProperty -> String +emitProperty withBounds cName p = let fName = cName ++ "_" ++ sanitizeIdent (compPropName p) pType = compPropType p decl = "(declare-fun " ++ fName ++ " (Entity) " ++ mapSmtType pType ++ ")\n" - in decl ++ concatMap (emitPropertyAssertion cName fName pType) (compConstraints p) + in decl ++ (if withBounds then concatMap (emitPropertyAssertion cName fName pType) (compConstraints p) else "") emitPropertyAssertion :: String -> String -> PropertyType -> BoundConstraint -> String emitPropertyAssertion cName fName pType c = @@ -78,40 +93,11 @@ propertyAssertionBody cName fName pType (BoundConstraint op val) = OpNe -> "distinct" in "(" ++ rel ++ " " ++ app ++ " " ++ lit ++ ")" --- | 'emitSMTDeclarations' with every property bound assertion named, so an unsat core can --- cite it. Returns the SMT text plus (name, description) pairs for each named bound. --- The consistency check asserts these bounds, so the unsat-core theory must assert them too, --- or ':explain' answers SAT for a contradiction ':solve' reported. +-- | 'emitSMTDeclarationsUnbounded' for the unsat-core theory, which must match the consistency +-- check: no bound assertions, hence no named bounds for a core to cite. Returns the SMT text +-- plus the (name, description) pairs of named bounds, which is empty. emitSMTDeclarationsNamed :: Registry -> (String, [(String, String)]) -emitSMTDeclarationsNamed reg = - let modelIR = compileRegistry reg - classes = irClasses modelIR - bounds = [ (cls, p, c) | cls <- classes, p <- compProperties cls, c <- compConstraints p ] - named = [ ( nm - , "(assert (! " ++ propertyAssertionBody cName fName (compPropType p) c ++ " :named " ++ nm ++ "))\n" - , "Property bound: " ++ compClassName cls ++ "." ++ compPropName p ++ " " - ++ compOpToString (constraintOp c) ++ " " ++ valueToString (constraintValue c) - ) - | (idx, (cls, p, c)) <- zip ([1..] :: [Int]) bounds - , let cName = sanitizeIdent (compClassName cls) - fName = cName ++ "_" ++ sanitizeIdent (compPropName p) - nm = "bound_" ++ show idx - ] - funDecls = concat [ "(declare-fun " ++ sanitizeIdent (compClassName cls) ++ "_" ++ sanitizeIdent (compPropName p) - ++ " (Entity) " ++ mapSmtType (compPropType p) ++ ")\n" - | cls <- classes, p <- compProperties cls ] - txt = "; Sort declarations\n" ++ - "(declare-sort Entity 0)\n\n" ++ - "; Entity Concept Constants\n" ++ - concatMap emitConceptConst classes ++ "\n" ++ - "; Subclass Hierarchy\n" ++ - "(declare-fun subClassOf (Entity Entity) Bool)\n" ++ - concatMap emitHierarchy classes ++ "\n" ++ - "; Property Functions and Bound Assertions\n" ++ - funDecls ++ concat [ a | (_, a, _) <- named ] ++ "\n" ++ - "; Relational Declarations\n" ++ - emitRelations (irRelations modelIR) ++ "\n" - in (txt, [ (n, d) | (n, _, d) <- named ]) +emitSMTDeclarationsNamed reg = (emitSMTDeclarationsUnbounded reg, []) -- | SMT-LIB2 numeral: plain decimal notation, reals keep a fraction, negatives as (- n). smtNumeral :: PropertyType -> Value -> String diff --git a/src/Emitters/Shacl.hs b/src/Emitters/Shacl.hs index 628c25b..1eb752c 100644 --- a/src/Emitters/Shacl.hs +++ b/src/Emitters/Shacl.hs @@ -41,7 +41,7 @@ emitNodeShape fmt cls = targetIri = fmt cName props = compProperties cls propShapes = map (emitPropertyShape fmt) props - condShapes = map (emitConditionalShape fmt) (compConditionalAxioms cls) + condShapes = map (emitConditionalShape fmt) (compEnforced cls) allShapes = propShapes ++ condShapes propBlock = if null allShapes then " sh:targetClass " ++ targetIri ++ " .\n\n" @@ -121,26 +121,16 @@ emitConditionalShape fmt ax = " ]\n" ++ " )" +-- | Total on what 'IR.normalizeCondition' produces; anything else was kept out upstream and +-- fails loudly here instead of becoming an empty shape (which conforms to everything). +-- An empty shape is written only for Top, where it is the right answer. emitShaclShapePattern :: (Name -> String) -> FOL -> String -emitShaclShapePattern fmt (Predicate op args) - | op `elem` ["eq", "ne", "gt", "gte", "lt", "lte"] = - case args of - [Var prop, Constant val] -> emitShaclPropBound fmt op prop val - [Constant val, Var prop] -> emitShaclPropBound fmt (invertCompOp op) prop val - _ -> "" - | otherwise = - case args of - (Var prop:_) -> - " sh:property [\n" ++ - " sh:path " ++ fmt prop ++ " ;\n" ++ - " sh:hasValue true ;\n" ++ - " ] ;\n" - [] -> - " sh:property [\n" ++ - " sh:path " ++ fmt op ++ " ;\n" ++ - " sh:hasValue true ;\n" ++ - " ] ;\n" - _ -> "" +emitShaclShapePattern fmt (Predicate op [Var prop, Constant val]) | op `elem` comparisonOps = emitShaclPropBound fmt op prop val +emitShaclShapePattern fmt (Predicate flag []) = + " sh:property [\n" ++ + " sh:path " ++ fmt flag ++ " ;\n" ++ + " sh:hasValue true ;\n" ++ + " ] ;\n" emitShaclShapePattern fmt (And p1 p2) = emitShaclShapePattern fmt p1 ++ emitShaclShapePattern fmt p2 emitShaclShapePattern fmt (Or p1 p2) = @@ -150,7 +140,9 @@ emitShaclShapePattern fmt (Or p1 p2) = " ) ;\n" emitShaclShapePattern fmt (Not p) = " sh:not [\n" ++ emitShaclShapePattern fmt p ++ " ] ;\n" -emitShaclShapePattern _ _ = "" +emitShaclShapePattern _ Top = "" +emitShaclShapePattern _ Bottom = " sh:not [ ] ;\n" +emitShaclShapePattern _ other = error ("SHACL emitter: untranslatable conditional " ++ formatFOL other) emitShaclPropBound :: (Name -> String) -> String -> Name -> String -> String emitShaclPropBound fmt op prop val = @@ -164,16 +156,17 @@ emitShaclPropBound fmt op prop val = | val `elem` ["False", "false"] -> " sh:hasValue false ;\n" | isNumber val -> " sh:hasValue " ++ val ++ " ;\n" | otherwise -> " sh:hasValue \"" ++ val ++ "\" ;\n" - "ne" -> " sh:not [ sh:hasValue " ++ val ++ " ] ;\n" - _ -> "" + "ne" -> " sh:not [ sh:hasValue " ++ shaclLiteral val ++ " ] ;\n" + _ -> error ("SHACL emitter: unknown comparison " ++ op) in " sh:property [\n" ++ pathLine ++ boundLine ++ " ] ;\n" -invertCompOp :: String -> String -invertCompOp "gt" = "lt" -invertCompOp "gte" = "lte" -invertCompOp "lt" = "gt" -invertCompOp "lte" = "gte" -invertCompOp op = op +-- | A Turtle literal for a constant: boolean, number or quoted string. +shaclLiteral :: String -> String +shaclLiteral val + | val `elem` ["True", "true"] = "true" + | val `elem` ["False", "false"] = "false" + | isNumber val = val + | otherwise = "\"" ++ val ++ "\"" isNumber :: String -> Bool isNumber s = case (readMaybe s :: Maybe Double) of diff --git a/src/Emitters/TPTP.hs b/src/Emitters/TPTP.hs index f4dbab0..6eb5615 100644 --- a/src/Emitters/TPTP.hs +++ b/src/Emitters/TPTP.hs @@ -31,7 +31,7 @@ emitTPTP reg = arithAxioms = concat [ "fof(arith_" ++ show i ++ ", axiom, (! [T] : ~(cmp_" ++ op1 ++ "(T, " ++ tptpConst a ++ ") & cmp_" ++ op2 ++ "(T, " ++ tptpConst b ++ ")))).\n" - | (i, ((op1, a), (op2, b))) <- zip ([1..] :: [Int]) (disjointBoundPairs (axioms reg)) + | (i, ((op1, a), (op2, b))) <- zip ([1..] :: [Int]) (disjointBoundPairs reg) ] header = "% TPTP First-Order Form (FOF) generated by OntoLogic\n\n" sections = filter (not . null) @@ -145,6 +145,9 @@ folToTPTP env bound f = case f of sb <- folToTPTP env bound b Right ("(" ++ sa ++ " " ++ op ++ " " ++ sb ++ ")") + -- A relation the ontology declares as gt/gte/lt/lte is a relation, not arithmetic. + isComparison op = op `elem` ["gt", "gte", "lt", "lte"] && op `notElem` envRelations env + predicate "eq" [t1, t2] = do s1 <- termToTPTP env bound t1 s2 <- termToTPTP env bound t2 @@ -157,12 +160,12 @@ folToTPTP env bound f = case f of predicate "!=" [t1, t2] = predicate "ne" [t1, t2] predicate op [Var p, Constant c] - | op `elem` ["gt", "gte", "lt", "lte"] = case bound of + | isComparison op = case bound of (subject : _) -> Right ("cmp_" ++ op ++ "(prop_" ++ sanitizeIdent p ++ "(" ++ tptpVar subject ++ "), " ++ tptpConst c ++ ")") [] -> Right ("cmp_" ++ op ++ "(prop_" ++ sanitizeIdent p ++ ", " ++ tptpConst c ++ ")") predicate op [Constant c, Var p] - | op `elem` ["gt", "gte", "lt", "lte"] = - predicate (invertCompOp op) [Var p, Constant c] + | isComparison op = + predicate (flipOp op) [Var p, Constant c] predicate name [] | Just PTBoolean <- Map.lookup name (envProps env) = case bound of @@ -212,9 +215,3 @@ tptpConst c = case map toLower c of VBool b -> if b then "c_true" else "c_false" VString s -> "c_" ++ sanitizeIdent s -invertCompOp :: String -> String -invertCompOp "gt" = "lt" -invertCompOp "gte" = "lte" -invertCompOp "lt" = "gt" -invertCompOp "lte" = "gte" -invertCompOp op = op diff --git a/src/Emitters/TypeScript.hs b/src/Emitters/TypeScript.hs index fd5e479..f5a474c 100644 --- a/src/Emitters/TypeScript.hs +++ b/src/Emitters/TypeScript.hs @@ -43,7 +43,7 @@ emitTypeScriptClass isCyclic cls = "export const " ++ cName ++ "Schema = " ++ sanitizeIdent pName ++ "Schema.extend({\n" ++ fields ++ "})" - refines = concatMap emitTsRefine (compConditionalAxioms cls) + refines = concatMap emitTsRefine (compEnforced cls) schemaDef = baseSchema ++ refines ++ ";\n\n" typeAlias = "export type " ++ cName ++ " = z.infer<typeof " ++ cName ++ "Schema>;\n\n" @@ -103,28 +103,25 @@ mapNumericBound _ = "" emitTsRefine :: ConditionalConstraint -> String emitTsRefine ax = "\n .refine((data: any) => {\n" ++ - " if (" ++ emitTsExpr (condPremise ax) ++ ") {\n" ++ - " return " ++ emitTsExpr (condConclusion ax) ++ ";\n" ++ - " }\n" ++ - " return true;\n" ++ + (case condPremise ax of + Top -> " return " ++ emitTsExpr (condConclusion ax) ++ ";\n" + pre -> " if (" ++ emitTsExpr pre ++ ") {\n" ++ + " return " ++ emitTsExpr (condConclusion ax) ++ ";\n" ++ + " }\n" ++ + " return true;\n") ++ " }, { message: \"Axiom violation: " ++ escapeJson (condDescription ax) ++ "\" })" +-- | Total on what 'IR.normalizeCondition' produces; anything else was kept out upstream and +-- fails loudly here instead of becoming a check that cannot fail. emitTsExpr :: FOL -> String -emitTsExpr (Predicate op args) - | op `elem` ["eq", "ne", "gt", "gte", "lt", "lte"] = - case args of - [Var prop, Constant val] -> emitTsBinary op prop val - [Constant val, Var prop] -> emitTsBinary (invertCompOp op) prop val - _ -> "true" - | otherwise = - case args of - (Var prop:_) -> "Boolean(data." ++ sanitizeIdent prop ++ ")" - [] -> "Boolean(data." ++ sanitizeIdent op ++ ")" - _ -> "true" +emitTsExpr (Predicate op [Var prop, Constant val]) | op `elem` comparisonOps = emitTsBinary op prop val +emitTsExpr (Predicate flag []) = "Boolean(data." ++ sanitizeIdent flag ++ ")" emitTsExpr (And p1 p2) = "(" ++ emitTsExpr p1 ++ " && " ++ emitTsExpr p2 ++ ")" emitTsExpr (Or p1 p2) = "(" ++ emitTsExpr p1 ++ " || " ++ emitTsExpr p2 ++ ")" emitTsExpr (Not p) = "!(" ++ emitTsExpr p ++ ")" -emitTsExpr _ = "true" +emitTsExpr Top = "true" +emitTsExpr Bottom = "false" +emitTsExpr other = error ("TypeScript emitter: untranslatable conditional " ++ formatFOL other) emitTsBinary :: String -> Name -> String -> String emitTsBinary op prop val = @@ -132,6 +129,8 @@ emitTsBinary op prop val = valExpr = case val of "True" -> "true" "False" -> "false" + "true" -> "true" + "false" -> "false" v | isNumber v -> v v -> "\"" ++ escapeJson v ++ "\"" tsOp = case op of @@ -141,16 +140,9 @@ emitTsBinary op prop val = "gte" -> ">=" "lt" -> "<" "lte" -> "<=" - _ -> "===" + _ -> error ("TypeScript emitter: unknown comparison " ++ op) in "(" ++ fld ++ " " ++ tsOp ++ " " ++ valExpr ++ ")" -invertCompOp :: String -> String -invertCompOp "gt" = "lt" -invertCompOp "gte" = "lte" -invertCompOp "lt" = "gt" -invertCompOp "lte" = "gte" -invertCompOp op = op - escapeJson :: String -> String escapeJson = escapeTargetString diff --git a/src/FOLTheory.hs b/src/FOLTheory.hs index 219268c..a86feec 100644 --- a/src/FOLTheory.hs +++ b/src/FOLTheory.hs @@ -364,6 +364,7 @@ translate env bound f = case f of | Map.member fn (envProps env) = do argStrs <- mapM translateTerm args Right ("(" ++ propFun fn ++ " " ++ unwords argStrs ++ ")") + | null args = Right (sanitizeIdent fn) -- a nullary function is a constant: "(f)" is not SMT-LIB | otherwise = do argStrs <- mapM translateTerm args Right ("(" ++ sanitizeIdent fn ++ " " ++ unwords argStrs ++ ")") @@ -383,10 +384,10 @@ translate env bound f = case f of | Just PTBoolean <- Map.lookup name (envProps env), Map.member v (envIndividuals env) = Right ("(" ++ propFun name ++ " " ++ individualConst v ++ ")") predicate name [t] - | name `elem` envConcepts env, isTermBoundOrConstant t = do + | name `elem` envConcepts env, isBoundEntityTerm t = do tStr <- translateTerm t Right ("(" ++ conceptPred name ++ " " ++ tStr ++ ")") - | Just PTBoolean <- Map.lookup name (envProps env), isTermBoundOrConstant t = do + | Just PTBoolean <- Map.lookup name (envProps env), isBoundEntityTerm t = do tStr <- translateTerm t Right ("(" ++ propFun name ++ " " ++ tStr ++ ")") @@ -402,7 +403,9 @@ translate env bound f = case f of Right ("(not (= " ++ s1 ++ " " ++ s2 ++ "))") predicate name args - | name `elem` envRelations env, length args >= 2, all isTermBoundOrConstant args = do + | name `elem` envRelations env, length args >= 2 + , length args == length (Map.findWithDefault ["Entity", "Entity"] name (envRelSigs env)) + , all isBoundEntityTerm args = do argStrs <- mapM translateTerm args Right ("(" ++ relPred name ++ " " ++ unwords argStrs ++ ")") @@ -435,10 +438,6 @@ translate env bound f = case f of isPropTerm (Var p) = Map.member p (envProps env) isPropTerm _ = False - isTermBoundOrConstant (Var v) = v `elem` bound || Map.member v (envIndividuals env) - isTermBoundOrConstant (Constant _) = True - isTermBoundOrConstant (Apply _ subArgs) = all isTermBoundOrConstant subArgs - termVarsBound (Var v) = v `elem` bound || Map.member v (envIndividuals env) termVarsBound (Constant _) = True termVarsBound (Apply _ subArgs) = all termVarsBound subArgs diff --git a/src/IR.hs b/src/IR.hs index e51cff0..5560f28 100644 --- a/src/IR.hs +++ b/src/IR.hs @@ -5,7 +5,8 @@ import GHC.Generics import Data.Graph (graphFromEdges, topSort) import qualified Data.Map as Map import qualified Data.Set as Set -import Data.List (maximumBy, minimumBy, nub) +import Data.List (maximumBy, minimumBy, nub, find) +import Text.Read (readMaybe) import Data.Ord (comparing) import OntoLogic @@ -26,6 +27,12 @@ data CompiledClass = CompiledClass , compParentClass :: Maybe Name , compProperties :: [CompiledProperty] , compConditionalAxioms :: [ConditionalConstraint] + -- ^ Conditionals as written (SQL reads relations between properties from these). + , compEnforced :: [ConditionalConstraint] + -- ^ What the application-tier emitters (Python, Java, Rust, Go, TypeScript, SHACL) check: + -- the conditionals every translator can state exactly, normalised, plus simple rules + -- no field bound carries (string and Boolean equality, disequality) with an empty + -- premise. Everything else is only in 'irUnmappedAxioms'. } deriving (Show, Eq, Generic) -- | Compiled representation of a relationship connecting two classes @@ -50,7 +57,7 @@ compileRegistry reg = let sortedConcepts = topologicalSortConcepts (concepts reg) classes = map (compileClass (concepts reg) (axioms reg) (properties reg) (relations reg)) sortedConcepts compiledRels = map (compileRelation (axioms reg)) (relations reg) - unmapped = filter (isUnmappedAxiom (concepts reg) (relations reg)) (axioms reg) + unmapped = filter (isUnmappedAxiom reg) (axioms reg) in ModelIR { irClasses = classes , irRelations = compiledRels @@ -70,6 +77,17 @@ compileClass :: [(Name, Maybe Name)] -> [FOL] -> [Property] -> [Relation] -> (Na compileClass conceptsList axs allProps allRels (name, parent) = let localMap = groupConstraints (getLocalConstraints name axs) mergedMap = groupConstraints (getInheritedConstraints name conceptsList axs) + look = visibleProperty conceptsList allProps name + -- A conditional an emitter would have to guess at (an undeclared property, a type that + -- does not fit, a shape no translator reads) is not handed to any emitter. It stays in + -- 'irUnmappedAxioms', so it is reported instead of turning into a check that cannot fail. + enforced = + [ c { condPremise = pre, condConclusion = con } + | c <- getLocalConditionalConstraints name axs + , Just pre <- [normalizeCondition look (condPremise c)] + , Just con <- [normalizeCondition look (condConclusion c)] + ] + ++ residualRequirements look (getLocalConstraints name axs) conditionalAxs = getLocalConditionalConstraints name axs -- Preserves original definition order from allProps @@ -91,6 +109,7 @@ compileClass conceptsList axs allProps allRels (name, parent) = , compParentClass = parent , compProperties = resolvedProps ++ resolvedRelProps , compConditionalAxioms = conditionalAxs + , compEnforced = enforced } compileRelation :: [FOL] -> Relation -> CompiledRelation @@ -157,30 +176,126 @@ groupConstraints consts = , isNumericValue val ] --- | Identify whether an axiom contains complex/conditional/relational logic unmapped to simple field bounds -isUnmappedAxiom :: [(Name, Maybe Name)] -> [Relation] -> FOL -> Bool -isUnmappedAxiom conceptsList rels ax = +-- | The property called @pname@ as seen from a class: declared on it or on an ancestor. +visibleProperty :: [(Name, Maybe Name)] -> [Property] -> Name -> Name -> Maybe Property +visibleProperty conceptsList props cls pname = + find (\p -> propName p == pname && domain p `elem` (cls : getAncestors cls conceptsList)) props + +-- | Conditionals are checked in generated code only when every atom is one a translator can +-- state exactly: a comparison of a declared, scalar property with a constant of a fitting +-- type, or a declared Boolean property used as a flag. The result is normalised so that all +-- emitters see one shape: @Predicate op [Var property, Constant value]@ (never @Eq@, never +-- the constant on the left) and @Predicate flag []@. 'Nothing' means: do not emit, report. +normalizeCondition :: (Name -> Maybe Property) -> FOL -> Maybe FOL +normalizeCondition look = go + where + go Top = Just Top + go Bottom = Just Bottom + go (And a b) = And <$> go a <*> go b + go (Or a b) = Or <$> go a <*> go b + go (Not a) = Not <$> go a + go (Implies a b) = Or <$> (Not <$> go a) <*> go b + go (Eq (Var p) (Constant v)) = atom "eq" p v + go (Eq (Constant v) (Var p)) = atom "eq" p v + go (Predicate op [Var p, Constant v]) | op `elem` comparisonOps = atom op p v + go (Predicate op [Constant v, Var p]) | op `elem` comparisonOps = atom (flipOp op) p v + go (Predicate n []) = flag n + go (Predicate n [Var v]) = maybe (flag v) Just (flag n) + go _ = Nothing + + atom op p v = do + prop <- look p + if scalar (propCardinality prop) && atomFits (rangeType prop) op v + then Just (Predicate op [Var p, Constant v]) + else Nothing + + flag n = do + prop <- look n + if scalar (propCardinality prop) && rangeType prop == PTBoolean + then Just (Predicate n []) + else Nothing + + scalar c = c `elem` [CardDefault, CardExactlyOne, CardZeroOrOne] + +comparisonOps :: [String] +comparisonOps = ["eq", "ne", "gt", "gte", "lt", "lte"] + +-- | Whether comparing a property of this type with the constant using the operator is meaningful. +atomFits :: PropertyType -> String -> String -> Bool +atomFits ty op v = case ty of + PTInteger -> numeric + PTFloat -> numeric + PTDouble -> numeric + PTBoolean -> op `elem` ["eq", "ne"] && v `elem` ["True", "true", "False", "false"] + PTString -> op `elem` ["eq", "ne"] && not numeric + PTCustom _ -> False + where + numeric = (readMaybe v :: Maybe Double) /= Nothing + +-- | A simple rule @(C x) => op(property, value)@ that no field bound can carry (a string or +-- Boolean value, equality, disequality) is still enforceable as a requirement with an empty +-- premise, provided the property is declared on C or an ancestor and the value fits its type. +residualRequirements :: (Name -> Maybe Property) -> [(Name, String, String)] -> [ConditionalConstraint] +residualRequirements look triples = + [ ConditionalConstraint Top atom' ("require " ++ formatFOL atom') + | (p, op, v) <- triples + , not (isFieldBound look (p, op, v)) + , Just atom' <- [normalizeCondition look (Predicate op [Var p, Constant v])] + ] + +-- | Whether a simple rule is carried by the numeric bound of a declared numeric property. +isFieldBound :: (Name -> Maybe Property) -> (Name, String, String) -> Bool +isFieldBound look (p, op, v) = + op `elem` ["gt", "gte", "lt", "lte"] + && (readMaybe v :: Maybe Double) /= Nothing + && maybe False (\prop -> rangeType prop `elem` [PTInteger, PTFloat, PTDouble]) (look p) + +-- | Find the declaration of a property as seen from a compiled class: the class itself or the +-- nearest ancestor that declares it. Returns the declaring class and the number of +-- inheritance steps between the two. +findDeclaredProperty :: [CompiledClass] -> CompiledClass -> Name -> Maybe (CompiledClass, Int, CompiledProperty) +findDeclaredProperty classes = go (0 :: Int) (length classes + 1) + where + go depth fuel cls pname + | fuel <= 0 = Nothing + | otherwise = case [ p | p <- compProperties cls, compPropName p == pname, not (compIsInherited p) ] of + (p : _) -> Just (cls, depth, p) + [] -> do + parentName <- compParentClass cls + parent <- find ((== parentName) . compClassName) classes + go (depth + 1) (fuel - 1) parent pname + +-- | Identify whether an axiom is not carried exactly by a field bound or a relation, so that +-- some target may have to drop or approximate it. Only a numeric ordering bound on a +-- declared numeric property of the concept (or an ancestor) counts as carried. +isUnmappedAxiom :: Registry -> FOL -> Bool +isUnmappedAxiom reg ax = case ax of - ForAll var (Implies cond body) -> - not (isSimpleConceptMembership var conceptsList cond && isSimpleFieldPredicate body) - TypedForAll var _ (Implies cond body) -> - not (isSimpleConceptMembership var conceptsList cond && isSimpleFieldPredicate body) - _ -> not (isKnownRelationAxiom rels ax) + ForAll var (Implies cond body) -> not (carried var cond body) + TypedForAll var _ (Implies cond body) -> not (carried var cond body) + _ -> not (isKnownRelationAxiom (relations reg) ax) where + conceptsList = concepts reg knownConceptNames = Set.fromList (map fst conceptsList) - isSimpleConceptMembership var _ (Predicate cName [Var v]) = + carried var (Predicate cName [Var v]) body = v == var && Set.member cName knownConceptNames - isSimpleConceptMembership _ _ _ = False + && all (\t -> isFieldBound (visibleProperty conceptsList (properties reg) cName) t) (atoms body) + && not (null (atoms body)) && simpleBody body + carried _ _ _ = False + + atoms (Predicate op [Var p, Constant c]) = [(p, op, c)] + atoms (And p1 p2) = atoms p1 ++ atoms p2 + atoms _ = [] - isSimpleFieldPredicate (Predicate _ [Var _, Constant _]) = True - isSimpleFieldPredicate (Eq (Var _) (Constant _)) = True - isSimpleFieldPredicate (And p1 p2) = isSimpleFieldPredicate p1 && isSimpleFieldPredicate p2 - isSimpleFieldPredicate _ = False + simpleBody (Predicate _ [Var _, Constant _]) = True + simpleBody (And p1 p2) = simpleBody p1 && simpleBody p2 + simpleBody _ = False - isKnownRelationAxiom knownRels (Predicate rName args) = - any (\r -> relName r == rName && length args >= 2) knownRels - isKnownRelationAxiom _ _ = False +isKnownRelationAxiom :: [Relation] -> FOL -> Bool +isKnownRelationAxiom knownRels (Predicate rName args) = + any (\r -> relName r == rName && length args >= 2) knownRels +isKnownRelationAxiom _ _ = False -- | How a target writes comments. data CommentStyle = LineComment String -- ^ a line prefix such as "//", "#", "--", ";" or "%%" diff --git a/src/IR/CNF.hs b/src/IR/CNF.hs index 364a6fe..2a01aee 100644 --- a/src/IR/CNF.hs +++ b/src/IR/CNF.hs @@ -1,3 +1,4 @@ +{-# OPTIONS_GHC -fno-omit-yields #-} {-# LANGUAGE DeriveGeneric #-} module IR.CNF ( VarId(..) diff --git a/src/IR/Clausify.hs b/src/IR/Clausify.hs index 7d672b2..f15f3a6 100644 --- a/src/IR/Clausify.hs +++ b/src/IR/Clausify.hs @@ -1,3 +1,4 @@ +{-# OPTIONS_GHC -fno-omit-yields #-} module IR.Clausify ( clausify , clausifyTheory @@ -83,6 +84,8 @@ desugarFOL other = other -- | Step 2: Push negations inward to form Negation Normal Form (NNF) toNNF :: FOL -> FOL toNNF (Not (Not p)) = toNNF p +toNNF (Not Top) = Bottom +toNNF (Not Bottom) = Top toNNF (Not (And p q)) = Or (toNNF (Not p)) (toNNF (Not q)) toNNF (Not (Or p q)) = And (toNNF (Not p)) (toNNF (Not q)) toNNF (Not (ForAll v p)) = Exists v (toNNF (Not p)) @@ -235,7 +238,7 @@ clausifyTheory reg = runClausifyM $ do -- numeric bounds exclude each other (see 'disjointBoundPairs'). let arithAxioms = [ ForAll "t" (Not (And (Predicate op1 [Var "t", Constant a]) (Predicate op2 [Var "t", Constant b]))) - | ((op1, a), (op2, b)) <- disjointBoundPairs (axioms reg) + | ((op1, a), (op2, b)) <- disjointBoundPairs reg ] let allAxioms = taxonomyAxioms ++ relationDomainAxioms ++ relationRangeAxioms ++ regAxioms ++ arithAxioms clauseLists <- mapM clausifyFOL allAxioms diff --git a/src/LSP.hs b/src/LSP.hs index 162a0d9..2993b3a 100644 --- a/src/LSP.hs +++ b/src/LSP.hs @@ -36,9 +36,9 @@ import Data.Char (isAlphaNum, isSpace, isHexDigit, chr, isUpper, isDigit) import OntoLogic import Parser (parseRegistry, parseRegistryWithSource) -import Linter (lintRegistryFindings, lintRegistryFindingsWithSource, LintFinding(..)) +import Linter (lintRegistryFindings, lintRegistryFindingsWithSource, LintFinding(..), isLintError) import IR (compileRegistry, irClasses, compClassName, compParentClass, compProperties, compPropName, compPropType, compConstraints, CompiledProperty, compCardinality, compDefaultValue) -import Solver (checkConsistencyWith, explainUnsatWith, extractModel, arithmeticCaveat, Prover(AutoProver), UnsatExplanation(..)) +import Solver (partialVerdict, usesSmtTheory, untranslatedAxioms, checkConsistencyWith, explainUnsatWith, extractModel, arithmeticCaveat, Prover(AutoProver), UnsatExplanation(..)) data LSPState = LSPState { lspDocs :: Map.Map String String -- URI -> Content @@ -298,7 +298,7 @@ updateDocWith impReg impErrs state uri content = case parse parseRegistryWithSource uri (T.pack content) of Left bundle -> let (l, c) = parseErrorPosition bundle - diag = mkDiag l c "ontologic-parser" (errorBundlePretty bundle) + diag = mkDiag 1 l c "ontologic-parser" (errorBundlePretty bundle) in ( state { lspDocs = Map.insert uri content (lspDocs state) } , publishDiagnostics uri [diag] ) Right (reg, sourceTbl) -> @@ -310,18 +310,19 @@ updateDocWith impReg impErrs state uri content = Nothing -> case lintSymbol f >>= symbolPosition content of Just (l, c) -> (l, c) Nothing -> (0, 0) - diags = [ mkDiag (importLine content e) 0 "ontologic-imports" e | e <- impErrs ] ++ - [ let (l, c) = place f in mkDiag l c "ontologic-linter" (lintMessage f) | f <- own ] + diags = [ mkDiag 1 (importLine content e) 0 "ontologic-imports" e | e <- impErrs ] ++ + [ let (l, c) = place f in mkDiag (if isLintError f then 1 else 2) l c "ontologic-linter" (lintMessage f) | f <- own ] newState = state { lspDocs = Map.insert uri content (lspDocs state) , lspRegistries = Map.insert uri merged (lspRegistries state) } in (newState, publishDiagnostics uri diags) -mkDiag :: Int -> Int -> String -> String -> String -mkDiag line char source msg = +-- | Severity follows the LSP spec: 1 = error, 2 = warning. +mkDiag :: Int -> Int -> Int -> String -> String -> String +mkDiag sev line char source msg = "{\"range\":{\"start\":{\"line\":" ++ show line ++ ",\"character\":" ++ show char ++ - "},\"end\":{\"line\":" ++ show line ++ ",\"character\":100}},\"severity\":1,\"source\":\"" ++ source ++ + "},\"end\":{\"line\":" ++ show line ++ ",\"character\":100}},\"severity\":" ++ show sev ++ ",\"source\":\"" ++ source ++ "\",\"message\":\"" ++ escapeJson msg ++ "\"}" publishDiagnostics :: String -> [String] -> String @@ -439,7 +440,7 @@ handleLSPRequestIO state raw reg = Map.findWithDefault emptyRegistry targetUri (lspRegistries state) case cmd of "ontologic.solve" -> do - res <- checkConsistencyWith AutoProver reg + res <- partialVerdict <$> skippedCount reg <*> checkConsistencyWith AutoProver reg caveat <- arithmeticCaveat AutoProver reg let (status, details) = case res of Sat _ -> ("sat", "Satisfiable (SAT): Consistent Model Found" ++ maybe "" (". " ++) caveat) @@ -456,7 +457,7 @@ handleLSPRequestIO state raw resp = "{\"jsonrpc\":\"2.0\",\"id\":" ++ formatId reqId ++ ",\"result\":{\"status\":\"" ++ status ++ "\",\"core\":" ++ coreStr ++ ",\"details\":\"" ++ escapeJson details ++ "\"}}" return (state, Just resp, []) "ontologic.inspectModel" -> do - res <- checkConsistencyWith AutoProver reg + res <- partialVerdict <$> skippedCount reg <*> checkConsistencyWith AutoProver reg let (status, modelStr) = case res of Sat m -> ("sat", maybe m id (extractModel res)) Unsat -> ("unsat", "No satisfying model (UNSAT)") @@ -477,6 +478,12 @@ handleLSPRequestIO state raw Just l -> return (Just l) Nothing -> searchImports word fs +-- | Number of axioms the SMT theory leaves out, when the answer comes from SMT-LIB. +skippedCount :: Registry -> IO Int +skippedCount reg = do + smtRoute <- usesSmtTheory AutoProver + return (if smtRoute then length (untranslatedAxioms reg) else 0) + getCompletions :: Registry -> String getCompletions reg = let keywords = ["def-concept", "def-property", "def-relation", "forall", "exists", "implies", "iff", "and", "or", "not", "import", "namespace"] diff --git a/src/Linter.hs b/src/Linter.hs index c665d07..9ae397f 100644 --- a/src/Linter.hs +++ b/src/Linter.hs @@ -8,35 +8,54 @@ import OntoLogic import Text.Read (readMaybe) import Linter.SAT (checkOntologySAT, DerivationChain(..)) +-- | How serious a finding is. Errors fail the run; warnings are reported and the run continues. +data Severity = SevError | SevWarning + deriving (Show, Eq, Ord) + -- | A lint message plus the symbol it is about, and optional source position coordinates -- for GCC/Rust-style "file:line:col: error: ..." diagnostics. data LintFinding = LintFinding' - { lintMessage :: String - , lintSymbol :: Maybe Name - , lintPos :: Maybe SourcePos + { lintMessage :: String + , lintSymbol :: Maybe Name + , lintPos :: Maybe SourcePos + , lintSeverity :: Severity } deriving (Show, Eq) pattern LintFinding :: String -> Maybe Name -> LintFinding -pattern LintFinding msg sym <- LintFinding' msg sym _ +pattern LintFinding msg sym <- LintFinding' msg sym _ _ where - LintFinding msg sym = LintFinding' msg sym Nothing + LintFinding msg sym = LintFinding' msg sym Nothing SevError pattern LintFindingWithPos :: String -> Maybe Name -> Maybe SourcePos -> LintFinding -pattern LintFindingWithPos msg sym pos = LintFinding' msg sym pos +pattern LintFindingWithPos msg sym pos <- LintFinding' msg sym pos _ + where + LintFindingWithPos msg sym pos = LintFinding' msg sym pos SevError {-# COMPLETE LintFinding #-} {-# COMPLETE LintFindingWithPos #-} +-- | A finding that is reported but does not fail the run. +lintWarning :: String -> Maybe Name -> LintFinding +lintWarning msg sym = LintFinding' msg sym Nothing SevWarning + +isLintError :: LintFinding -> Bool +isLintError f = lintSeverity f == SevError + -- | Formatted GCC/Rust-style diagnostic string: "file:line:col: error: <message>" formatLintFinding :: LintFinding -> String formatLintFinding f = case lintPos f of - Just pos -> formatSourcePos pos ++ ": error: " ++ lintMessage f - Nothing -> "error: " ++ lintMessage f + Just pos -> formatSourcePos pos ++ ": " ++ word ++ ": " ++ lintMessage f + Nothing -> word ++ ": " ++ lintMessage f + where word = if isLintError f then "error" else "warning" -- | Messages only. Kept so every existing caller and expectation is unaffected. lintRegistry :: Registry -> [String] lintRegistry = map lintMessage . lintRegistryFindings +-- | Messages of the findings that fail the run. +lintRegistryErrors :: Registry -> [LintFinding] +lintRegistryErrors = filter isLintError . lintRegistryFindings + -- | Default lint findings without source table lintRegistryFindings :: Registry -> [LintFinding] lintRegistryFindings = lintRegistryFindingsWithSource emptySourceTable @@ -47,7 +66,8 @@ lintRegistryFindingsWithSource tbl reg = map (resolveFindingPos tbl) $ checkSymbolIntegrity reg ++ checkCircularInheritance (Map.fromList $ concepts reg) ++ - checkContradictoryAxioms (axioms reg) ++ + checkContradictoryAxioms (map fst (concepts reg)) (axioms reg) ++ + checkUndeclaredAxiomSymbols reg ++ checkGlobalPropertyContradictions reg ++ checkSemanticSATContradictions reg @@ -60,12 +80,12 @@ lintRegistryDiagnosticsWithSource :: SourceTable -> Registry -> [String] lintRegistryDiagnosticsWithSource tbl reg = map formatLintFinding (lintRegistryFindingsWithSource tbl reg) resolveFindingPos :: SourceTable -> LintFinding -> LintFinding -resolveFindingPos tbl (LintFinding' msg sym mPos) = +resolveFindingPos tbl (LintFinding' msg sym mPos sev) = case mPos of - Just _ -> LintFinding' msg sym mPos + Just _ -> LintFinding' msg sym mPos sev Nothing -> let foundPos = sym >>= lookupSourceTable tbl - in LintFinding' msg sym foundPos + in LintFinding' msg sym foundPos sev checkSymbolIntegrity :: Registry -> [LintFinding] checkSymbolIntegrity reg = @@ -75,13 +95,15 @@ checkSymbolIntegrity reg = checkDuplicateNamespaces (namespaces reg) ++ checkUndeclaredParents (concepts reg) ++ checkUndeclaredDomains (concepts reg) (properties reg) ++ + checkUndeclaredPropertyTypes (concepts reg) (properties reg) ++ checkUndeclaredRelationEndpoints (concepts reg) (relations reg) checkDuplicateNamespaces :: [NamespaceDecl] -> [LintFinding] checkDuplicateNamespaces nsList = + -- The same prefix bound to the same URI twice is harmless; two URIs is a clash. [ LintFinding ("Duplicate namespace prefix declaration: " ++ p) (Just p) - | (p, count) <- countOccurrences (map nsPrefix nsList) - , count > 1 + | (p, uris) <- Map.toList (Map.fromListWith Set.union [ (nsPrefix n, Set.singleton (nsUri n)) | n <- nsList ]) + , Set.size uris > 1 ] checkDuplicateConcepts :: [(Name, Maybe Name)] -> [LintFinding] @@ -122,6 +144,16 @@ checkUndeclaredDomains cList pList = , not (Set.member (domain p) knownConcepts) ] +-- | A property range must be a built-in type or a declared concept. +checkUndeclaredPropertyTypes :: [(Name, Maybe Name)] -> [Property] -> [LintFinding] +checkUndeclaredPropertyTypes cList pList = + let knownConcepts = Set.fromList (map fst cList) + in [ LintFinding ("Undeclared property type: " ++ t ++ " in property " ++ propName p) (Just (propName p)) + | p <- pList + , PTCustom t <- [rangeType p] + , not (Set.member t knownConcepts) + ] + checkUndeclaredRelationEndpoints :: [(Name, Maybe Name)] -> [Relation] -> [LintFinding] checkUndeclaredRelationEndpoints cList rList = let knownConcepts = Set.fromList (map fst cList) @@ -150,41 +182,35 @@ checkCircularInheritance conceptMap = Just Nothing -> [] -- No parent Just (Just parent) -> findCycle (node : path) (Set.insert node visited) parent -checkContradictoryAxioms :: [FOL] -> [LintFinding] -checkContradictoryAxioms axs = concatMap checkAxiomContradiction axs +-- | Contradictions inside one axiom. Only the conjuncts that hold unconditionally are +-- examined: the axiom itself, through untyped quantifiers and typed ones whose sort is +-- not a concept. Anything under an implication, a disjunction, a negation or a +-- concept-guarded binder holds only conditionally (the guard may be empty), so a clash +-- there does not make the theory unsatisfiable. +checkContradictoryAxioms :: [Name] -> [FOL] -> [LintFinding] +checkContradictoryAxioms cs axs = concatMap (checkFormulaContradiction . getConjuncts . unconditional cs) axs --- Recursively check an FOL term for contradictions -checkAxiomContradiction :: FOL -> [LintFinding] -checkAxiomContradiction ax = - let subFormulas = getSubFormulas ax - in concatMap (checkFormulaContradiction . getConjuncts) subFormulas +unconditional :: [Name] -> FOL -> FOL +unconditional cs = go + where + go (ForAll _ f) = go f + go (Exists _ f) = go f + go (TypedForAll _ s f) | s `notElem` cs = go f + go (TypedExists _ s f) | s `notElem` cs = go f + go f = f -- Flatten any nested logical ANDs getConjuncts :: FOL -> [FOL] getConjuncts (And p1 p2) = getConjuncts p1 ++ getConjuncts p2 getConjuncts p = [p] --- Find logical subformulas where conjuncts are grouped -getSubFormulas :: FOL -> [FOL] -getSubFormulas f = f : case f of - And p1 p2 -> getSubFormulas p1 ++ getSubFormulas p2 - Or p1 p2 -> getSubFormulas p1 ++ getSubFormulas p2 - Not p -> getSubFormulas p - Implies p1 p2 -> getSubFormulas p1 ++ getSubFormulas p2 - Iff p1 p2 -> getSubFormulas p1 ++ getSubFormulas p2 - ForAll _ p -> getSubFormulas p - Exists _ p -> getSubFormulas p - TypedForAll _ _ p -> getSubFormulas p - TypedExists _ _ p -> getSubFormulas p - _ -> [] - checkFormulaContradiction :: [FOL] -> [LintFinding] checkFormulaContradiction conjuncts = checkPropositionalContradiction conjuncts ++ checkRangeContradiction conjuncts ++ checkBottomContradiction conjuncts checkBottomContradiction :: [FOL] -> [LintFinding] checkBottomContradiction conjuncts = - [ LintFinding "Axiom contradiction: bottom (false) asserted." Nothing | Bottom `elem` conjuncts ] + [ LintFinding "Axiom contradiction: bottom (false) asserted." Nothing | any (`elem` [Bottom, Not Top]) conjuncts ] checkPropositionalContradiction :: [FOL] -> [LintFinding] checkPropositionalContradiction conjuncts = @@ -240,8 +266,8 @@ checkGlobalPropertyContradictions reg = -- | Contradictions between a concept's own bounds and the bounds it has or inherits. checkConceptAxioms :: Registry -> Name -> [LintFinding] checkConceptAxioms reg conceptName = - let local = getLocalConstraints conceptName (axioms reg) - allC = getInheritedConstraints conceptName (concepts reg) (axioms reg) + let local = guardedConstraints reg conceptName + allC = concatMap (guardedConstraints reg) (conceptName : getAncestors conceptName (concepts reg)) in map (\m -> LintFinding m (Just conceptName)) $ nubOrd [ "Cross-axiom contradiction on " ++ conceptName ++ "." ++ p1 ++ ": " ++ o1 ++ " " ++ v1 ++ " and " ++ o2 ++ " " ++ v2 | (p1, o1, v1) <- local @@ -250,10 +276,57 @@ checkConceptAxioms reg conceptName = , evalPairContradiction (o1, v1) (o2, v2) || evalPairContradiction (o2, v2) (o1, v1) ] +-- | Bounds that an axiom places on a concept, read only where the binder guard is no narrower +-- than the concept: (forall ((x Adult)) (implies (Member x) ...)) binds Adult-and-Member +-- members, not every Member, so it yields nothing for Member. +guardedConstraints :: Registry -> Name -> [(Name, String, String)] +guardedConstraints reg conceptName = concatMap (extract []) (axioms reg) + where + cs = map fst (concepts reg) + wideEnough s = s == conceptName || s `elem` getAncestors conceptName (concepts reg) || s `notElem` cs + extract bound (ForAll v body) = extract (v : bound) body + extract bound (TypedForAll v s body) + | wideEnough s = extract (v : bound) body + | otherwise = [] + extract bound (Implies (Predicate name [Var x]) body) + | name == conceptName && x `elem` bound = simple body + extract _ _ = [] + simple (Predicate op [Var prop, Constant val]) = [(prop, op, val)] + simple (Eq (Var prop) (Constant val)) = [(prop, "eq", val)] + simple (And p1 p2) = simple p1 ++ simple p2 + simple _ = [] + +-- | Names an axiom uses that nothing declares. A warning: the axiom may still be satisfiable. +checkUndeclaredAxiomSymbols :: Registry -> [LintFinding] +checkUndeclaredAxiomSymbols reg = + [ lintWarning ("Undeclared " ++ kind ++ " in axiom: " ++ n) (Just n) + | (kind, n) <- nubOrd (concatMap (symbolsOf []) (axioms reg)) + , not (Set.member n declared) + ] + where + declared = Set.fromList $ + map fst (concepts reg) ++ map propName (properties reg) ++ map relName (relations reg) + ++ map fst (individuals reg) ++ comparisons + comparisons = ["gt", "gte", "lt", "lte", "eq", "ne"] + symbolsOf bound f = case f of + Predicate op [Var prop, _] | op `elem` comparisons -> [ ("property", prop) | prop `notElem` bound ] + Predicate p _ -> [("predicate", p)] + And a b -> symbolsOf bound a ++ symbolsOf bound b + Or a b -> symbolsOf bound a ++ symbolsOf bound b + Implies a b -> symbolsOf bound a ++ symbolsOf bound b + Iff a b -> symbolsOf bound a ++ symbolsOf bound b + Not a -> symbolsOf bound a + ForAll v a -> symbolsOf (v : bound) a + Exists v a -> symbolsOf (v : bound) a + TypedForAll v _ a -> symbolsOf (v : bound) a + TypedExists v _ a -> symbolsOf (v : bound) a + Eq (Var prop) (Constant _) -> [ ("property", prop) | prop `notElem` bound ] + _ -> [] + -- | Propositional SAT & Horn resolution contradiction check. -- Detects transitive implications violating disjointness or unsatisfiable concepts in sub-millisecond pure Haskell. checkSemanticSATContradictions :: Registry -> [LintFinding] checkSemanticSATContradictions reg = map chainToFinding (checkOntologySAT reg) where - chainToFinding chain = LintFinding (chainFormatted chain) (chainConcept chain) + chainToFinding chain = lintWarning (chainFormatted chain) (chainConcept chain) diff --git a/src/Linter/SAT.hs b/src/Linter/SAT.hs index 2a2fffc..8e7aece 100644 --- a/src/Linter/SAT.hs +++ b/src/Linter/SAT.hs @@ -69,26 +69,52 @@ data DerivationChain = DerivationChain -- | Strip the quantifier prefix from a FOL formula, keeping concept-sort guards: -- (forall ((x C)) f) becomes (implies (C x) f) and (exists ((x C)) f) becomes (and (C x) f). -- Sorts that are not concepts (Int, String, ...) carry no guard. +-- A unary atom over a symbol the prefix does not bind is a ground fact about +-- an individual: it becomes a separate atom, never the universal one. stripQuantifiers :: [Name] -> FOL -> FOL -stripQuantifiers cs = go +stripQuantifiers cs = go [] where - go (ForAll _ f) = go f - go (Exists _ f) = go f - go (TypedForAll v s f) - | s `elem` cs = Implies (Predicate s [Var v]) (go f) - | otherwise = go f - go (TypedExists v s f) - | s `elem` cs = And (Predicate s [Var v]) (go f) - | otherwise = go f - go f = f - --- | Count the existential quantifiers in the formula's outer quantifier prefix. -countExistentials :: FOL -> Int -countExistentials (ForAll _ f) = countExistentials f -countExistentials (TypedForAll _ _ f) = countExistentials f -countExistentials (Exists _ f) = 1 + countExistentials f -countExistentials (TypedExists _ _ f) = 1 + countExistentials f -countExistentials _ = 0 + go bound (ForAll v f) = go (v : bound) f + go bound (Exists v f) = go (v : bound) f + go bound (TypedForAll v s f) + | s `elem` cs = Implies (Predicate s [Var v]) (go (v : bound) f) + | otherwise = go (v : bound) f + go bound (TypedExists v s f) + | s `elem` cs = And (Predicate s [Var v]) (go (v : bound) f) + | otherwise = go (v : bound) f + go bound f = groundFree bound f + +groundFree :: [Name] -> FOL -> FOL +groundFree bound = walk + where + walk (Predicate p [Var v]) | v `notElem` bound = Predicate p [Constant v] + walk (And a b) = And (walk a) (walk b) + walk (Or a b) = Or (walk a) (walk b) + walk (Not a) = Not (walk a) + walk (Implies a b) = Implies (walk a) (walk b) + walk (Iff a b) = Iff (walk a) (walk b) + walk f = f + +-- | How an axiom's quantifier prefix constrains the propositional abstraction. +data QuantShape = Universal | Witness | Dependent + deriving (Eq, Show) + +-- | A prefix with no existential is Universal. A single existential not under +-- a universal is a Witness. An existential under a universal depends on it +-- and cannot be collapsed onto one element, so it is dropped (Dependent), +-- as is any prefix with more than one existential. +quantShape :: FOL -> QuantShape +quantShape = go False (0 :: Int) + where + go _ n (ForAll _ f) = go True n f + go _ n (TypedForAll _ _ f) = go True n f + go seenAll n (Exists _ f) + | seenAll = Dependent + | otherwise = go seenAll (n + 1) f + go seenAll n (TypedExists _ _ f) + | seenAll = Dependent + | otherwise = go seenAll (n + 1) f + go _ n _ = if n == 0 then Universal else if n == 1 then Witness else Dependent -- | Convert formula to Negation Normal Form (NNF). toNNF :: FOL -> FOL @@ -147,8 +173,8 @@ registryToClauses reg = (inheritanceClauses ++ concat universals, existentials) | (child, Just parent) <- concepts reg ] indexed = zip [1..] (axioms reg) - universals = [ axiomClauses idx ax | (idx, ax) <- indexed, countExistentials ax == 0 ] - existentials = [ axiomClauses idx ax | (idx, ax) <- indexed, countExistentials ax == 1 ] + universals = [ axiomClauses idx ax | (idx, ax) <- indexed, quantShape ax == Universal ] + existentials = [ axiomClauses idx ax | (idx, ax) <- indexed, quantShape ax == Witness ] axiomClauses idx ax = map (\lits -> Clause lits (classifyOrigin idx ax lits)) (toCNFClauses (toNNF (stripQuantifiers conceptNames ax))) classifyOrigin idx ax lits = diff --git a/src/Loader.hs b/src/Loader.hs index 31d6fd9..7902f57 100644 --- a/src/Loader.hs +++ b/src/Loader.hs @@ -11,17 +11,20 @@ module Loader , resolveImportsWithSource , findImportFile , loadImportFrom + , loadRegistryWithOptions + , ontologicVersion ) where import qualified Data.Text.IO as TIO import qualified Data.Map as Map import Text.Megaparsec (parse, errorBundlePretty) -import System.FilePath ((</>), takeDirectory, isAbsolute, normalise) +import System.FilePath ((</>), takeDirectory, isAbsolute, normalise, takeExtension) import System.Directory (doesFileExist, doesDirectoryExist, canonicalizePath) import System.Environment (lookupEnv, getExecutablePath) import System.FilePath (splitSearchPath) import Control.Monad (filterM) -import Paths_ontologic (getDataDir) +import Paths_ontologic (getDataDir, version) +import Data.Version (showVersion) import qualified Data.Set as Set import Data.List (intercalate) @@ -44,6 +47,17 @@ stdlibSearchPaths = do ] +-- | Package version, taken from the cabal package so it cannot drift. +ontologicVersion :: String +ontologicVersion = showVersion version + +-- | Load with extra search paths; the Bool permits absolute import paths +-- (the --allow-absolute-imports flag). +loadRegistryWithOptions :: Bool -> [FilePath] -> FilePath -> IO (Either String (Registry, SourceTable)) +loadRegistryWithOptions allowAbs extra rootFile = do + defaults <- stdlibSearchPaths + loadWith allowAbs (extra ++ defaults) rootFile + -- | Load a .logic file and its transitive imports returning (Registry, SourceTable). loadRegistryWithImportsAndSource :: FilePath -> IO (Either String (Registry, SourceTable)) loadRegistryWithImportsAndSource = loadRegistryWithLibPathsAndSource [] @@ -56,13 +70,16 @@ loadRegistryWithLibPathsAndSource extra rootFile = do -- | Load with explicit search paths returning (Registry, SourceTable). loadRegistryWithImportsFromSearchPathsAndSource :: [FilePath] -> FilePath -> IO (Either String (Registry, SourceTable)) -loadRegistryWithImportsFromSearchPathsAndSource searchPaths rootFile = do +loadRegistryWithImportsFromSearchPathsAndSource = loadWith False + +loadWith :: Bool -> [FilePath] -> FilePath -> IO (Either String (Registry, SourceTable)) +loadWith allowAbs searchPaths rootFile = do exists <- doesFileExist rootFile if not exists then return $ Left ("File not found: " ++ rootFile) else do canonRoot <- canonicalizePath rootFile - resolveImportsWithSource searchPaths canonRoot + resolveImportsWithSource' allowAbs searchPaths canonRoot -- | Load a .logic file and its transitive imports using the default library paths. loadRegistryWithImports :: FilePath -> IO (Either String Registry) @@ -79,18 +96,27 @@ loadRegistryWithImportsFromSearchPaths searchPaths rootFile = -- | Locate one import by name in the given directories, in order. findImportFile :: [FilePath] -> FilePath -> IO (Either String FilePath) -findImportFile _ rawPath | isAbsolute rawPath = do +findImportFile = findImportFile' False + +-- | Imports must name a .logic file, so an import can never be used to read +-- arbitrary files. Absolute paths are refused unless explicitly allowed. +findImportFile' :: Bool -> [FilePath] -> FilePath -> IO (Either String FilePath) +findImportFile' _ _ rawPath | takeExtension rawPath /= ".logic" = + return $ Left ("Import must name a .logic file: " ++ rawPath) +findImportFile' False _ rawPath | isAbsolute rawPath = + return $ Left ("Absolute import paths are not allowed (use --allow-absolute-imports): " ++ rawPath) +findImportFile' _ _ rawPath | isAbsolute rawPath = do exists <- doesFileExist rawPath if exists then return $ Right (normalise rawPath) else return $ Left ("Import not found: " ++ rawPath) -findImportFile [] rawPath = return $ Left ("Import not found: " ++ rawPath) -findImportFile (dir:dirs) rawPath = do +findImportFile' _ [] rawPath = return $ Left ("Import not found: " ++ rawPath) +findImportFile' allowAbs (dir:dirs) rawPath = do let candidate = dir </> rawPath exists <- doesFileExist candidate if exists then return $ Right (normalise candidate) - else findImportFile dirs rawPath + else findImportFile' allowAbs dirs rawPath -- | Resolve one import by name and load it with its own transitive imports. -- The language server needs the resolved path as well as the registry. @@ -110,7 +136,10 @@ resolveImports searchPaths rootCanonPath = fmap (fmap fst) (resolveImportsWithSo -- | Internal recursive import resolver returning Registry and SourceTable resolveImportsWithSource :: [FilePath] -> FilePath -> IO (Either String (Registry, SourceTable)) -resolveImportsWithSource searchPaths rootCanonPath = do +resolveImportsWithSource = resolveImportsWithSource' False + +resolveImportsWithSource' :: Bool -> [FilePath] -> FilePath -> IO (Either String (Registry, SourceTable)) +resolveImportsWithSource' allowAbs searchPaths rootCanonPath = do res <- go Set.empty [] rootCanonPath case res of Left err -> return $ Left err @@ -143,7 +172,7 @@ resolveImportsWithSource searchPaths rootCanonPath = do foldMImport :: [FilePath] -> Set.Set FilePath -> [FilePath] -> Registry -> SourceTable -> [ImportDecl] -> IO (Either String (Set.Set FilePath, Registry, SourceTable)) foldMImport _ finished _ accReg accTbl [] = return $ Right (finished, accReg, accTbl) foldMImport searchDirs finished visiting accReg accTbl (imp:rest) = do - foundPathRes <- findImportFile searchDirs (importPath imp) + foundPathRes <- findImportFile' allowAbs searchDirs (importPath imp) case foundPathRes of Left err -> return $ Left err Right targetPath -> do diff --git a/src/Main.hs b/src/Main.hs index 4e1b8a5..c72200b 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -4,25 +4,32 @@ import Options.Applicative import System.Exit (exitFailure, exitWith, ExitCode(..)) import System.IO (hPutStrLn, stderr) import System.Process (callProcess) -import System.Directory (createDirectoryIfMissing) +import System.Directory (createDirectoryIfMissing, findExecutable) import System.FilePath ((</>)) import Control.Exception (try, IOException) +import Control.Monad (when) +import Data.Maybe (isNothing) import OntoLogic import IR (compileRegistry, irUnmappedAxioms) import IR.CNF (formatCNFTheory) import IR.Clausify (clausifyTheory) -import Loader (loadRegistryWithLibPathsAndSource) -import Linter (lintRegistryDiagnosticsWithSource) +import Loader (loadRegistryWithOptions, ontologicVersion) +import Linter (lintRegistryFindingsWithSource, formatLintFinding, isLintError) import REPL (runREPL) +import GHC.Clock (getMonotonicTime) import Solver ( checkConsistencyWithOptions , findUnsatConceptsWithOptions , explainUnsatWithOptions , untranslatedAxioms + , usesSmtTheory + , clampTimeoutSeconds + , defaultSolveTimeoutSeconds , arithmeticCaveat , resolveProver , solverExitCode + , partialVerdict , worst , extractModel , UnsatExplanation(..) @@ -55,10 +62,11 @@ data Args = Args , solveTimeout :: Maybe Int , solveMemory :: Maybe Int , libPaths :: [String] + , allowAbsImports :: Bool } argsParser :: ParserInfo Args -argsParser = info (helper <*> opts) fullDesc +argsParser = info (helper <*> versionOpt <*> opts) fullDesc where opts = Args <$> optional (strOption (long "input" <> short 'i' <> help "Path to .logic file")) @@ -67,7 +75,7 @@ argsParser = info (helper <*> opts) fullDesc <*> optional (strOption (long "java-package" <> help "Java package for generated models (default: ontologic.generated)")) <*> optional (strOption (long "base-iri" <> metavar "IRI" <> help "Base IRI for OWL/SHACL output (default: the ontology's first namespace)")) <*> optional (strOption (long "prover" <> short 'p' <> help "Theorem prover backend: z3, cvc5, vampire, native, auto (default: auto)")) - <*> optional (strOption (long "neo4j-edition" <> metavar "EDITION" <> help "Neo4j Edition for constraints: community, enterprise (default: enterprise)")) + <*> optional (option neo4jEditionReader (long "neo4j-edition" <> metavar "EDITION" <> help "Neo4j Edition for constraints: community, enterprise (default: enterprise)")) <*> switch (long "render" <> help "Render output to image (requires mmdc or d2 CLI installed)") <*> switch (long "repl" <> help "Start interactive ontology REPL session") <*> switch (long "cnf" <> help "Emit ontology clausal normal form (CNF) theory to stdout") @@ -80,12 +88,20 @@ argsParser = info (helper <*> opts) fullDesc <*> optional (option positiveInt (long "solve-timeout" <> short 'T' <> metavar "SECONDS" <> help "Solver time limit in seconds, a positive integer (enforced for Z3, CVC5, Vampire, and Native)")) <*> optional (option positiveInt (long "solve-memory" <> metavar "MB" <> help "Solver memory limit in megabytes, a positive integer (Z3 only; ignored with a warning for other provers)")) <*> many (strOption (long "lib-path" <> metavar "DIR" <> help "Extra directory searched for imports (repeatable; also $ONTOLOGIC_PATH)")) + <*> switch (long "allow-absolute-imports" <> help "Permit absolute paths in (import ...) declarations (refused by default)") + + versionOpt = infoOption ("ontologic " ++ ontologicVersion) (long "version" <> help "Show version") -- | Reject 0 and negatives: backends disagree on what they mean (Z3 reads -T:0 as -- "no limit", System.Timeout reads 0 as "already expired"). +neo4jEditionReader :: ReadM String +neo4jEditionReader = eitherReader $ \s -> case parseNeo4jEdition s of + Just _ -> Right s + Nothing -> Left ("unknown Neo4j edition '" ++ s ++ "'; expected community or enterprise") + positiveInt :: ReadM Int positiveInt = eitherReader $ \s -> case reads s of - [(n, "")] | n > 0 -> Right n + [(n, "")] | n > (0 :: Integer) -> Right (fromInteger (min n 2147483647)) _ -> Left ("expected a positive integer, got '" ++ s ++ "'") main :: IO () @@ -98,7 +114,7 @@ main = do else case input args of Nothing -> putStrLn "Error: --input is required (or use --repl / --lsp)" >> exitFailure Just inpFile -> do - loadRes <- loadRegistryWithLibPathsAndSource (libPaths args) inpFile + loadRes <- loadRegistryWithOptions (allowAbsImports args) (libPaths args) inpFile case loadRes of Left err -> do putStrLn err @@ -107,7 +123,10 @@ main = do let registry = if freeConstants args then promoteFreeConstants rawRegistry else rawRegistry - errors = lintRegistryDiagnosticsWithSource sourceTable registry + findings = lintRegistryFindingsWithSource sourceTable registry + errors = map formatLintFinding (filter isLintError findings) + warnings = map formatLintFinding (filter (not . isLintError) findings) + mapM_ putStrLn warnings if not (null errors) then mapM_ putStrLn errors >> exitFailure else if cnfMode args @@ -124,29 +143,31 @@ runSolverCheck isFreeConsts showExplain showModel maybeP maybeTimeout maybeMem r case resolveProver maybeP of Left msg -> putStrLn msg >> exitFailure Right prover -> do - let solverOpts = SolverOptions - { optTimeoutSeconds = maybeTimeout + started <- getMonotonicTime + let effectiveSeconds = maybe defaultSolveTimeoutSeconds clampTimeoutSeconds maybeTimeout + solverOpts = SolverOptions + { optTimeoutSeconds = Just effectiveSeconds , optMemoryLimitMb = maybeMem } case (maybeMem, prover) of (Just _, Z3) -> return () - (Just _, AutoProver) -> hPutStrLn stderr "⚠️ --solve-memory is applied only if Z3 is the prover selected; other backends run without a memory limit." + (Just _, AutoProver) -> do + z3 <- findExecutable "z3" + when (isNothing z3) $ + hPutStrLn stderr "⚠️ --solve-memory applies only to Z3, which is not on PATH; the backend that runs has no memory limit." (Just _, p) -> hPutStrLn stderr ("⚠️ --solve-memory is not supported by " ++ proverName p ++ " and is ignored.") (Nothing, _) -> return () if isFreeConsts then putStrLn "ℹ️ Free constants mode enabled (--free-constants): undeclared free variables are treated as Entity constants." else return () - let skipped = untranslatedAxioms reg - if null skipped then return () else do - putStrLn ("⚠️ " ++ show (length skipped) ++ " axiom(s) were not sent to the solver:") - mapM_ (\(ax, why) -> putStrLn (" - " ++ show ax ++ " (" ++ why ++ ")")) skipped - + -- The notice describes the SMT-LIB theory: Vampire and the native prover do not read it. + smtRoute <- usesSmtTheory prover + let skipped = if smtRoute then untranslatedAxioms reg else [] -- Consistency: can the axioms be satisfied at all? - res <- checkConsistencyWithOptions solverOpts prover reg + res <- partialVerdict (length skipped) <$> checkConsistencyWithOptions solverOpts prover reg case res of Sat _ -> do - putStrLn $ "✅ SMT Satisfiable (SAT) — Ontology is logically consistent" ++ - (if null skipped then "." else " for the " ++ show (length (axioms reg) - length skipped) ++ " axioms checked.") + putStrLn "✅ SMT Satisfiable (SAT) — Ontology is logically consistent." if showModel then case extractModel res of Just m -> putStrLn ("\n📋 SMT Model Valuation:\n" ++ m) @@ -165,9 +186,23 @@ runSolverCheck isFreeConsts showExplain showModel maybeP maybeTimeout maybeMem r else return () Unknown out -> putStrLn $ "⚠️ SMT Solver Result (unknown): " ++ out SolverError err -> putStrLn $ "❌ SMT Solver Error: " ++ err + -- The axioms the verdict does not cover come right after it. + if null skipped then return () else do + putStrLn ("⚠️ " ++ show (length skipped) ++ " axiom(s) were not sent to the solver:") + mapM_ (\(ax, why) -> putStrLn (" - " ++ show ax ++ " (" ++ why ++ ")")) skipped -- Coherence: which concepts can have no instance at all? - coh <- findUnsatConceptsWithOptions solverOpts prover reg + -- The native prover has no process to kill, so the limit is one budget shared by the + -- consistency check and the coherence sweep rather than a fresh limit for each. + elapsed <- subtract started <$> getMonotonicTime + let sharedBudget = prover == NativeProver || (prover == AutoProver && not smtRoute) + limit = effectiveSeconds + remaining = limit - ceiling elapsed + coh <- if sharedBudget && remaining < 1 + then return (Left "the time limit was used up before the concept check could start") + else findUnsatConceptsWithOptions + (if sharedBudget then solverOpts { optTimeoutSeconds = Just remaining } else solverOpts) + prover reg coherenceCode <- case coh of Left err -> do putStrLn ("⚠️ Concept coherence check could not run: " ++ err) diff --git a/src/OntoLogic.hs b/src/OntoLogic.hs index 8925848..4ff97f3 100644 --- a/src/OntoLogic.hs +++ b/src/OntoLogic.hs @@ -338,7 +338,8 @@ deduplicateRegistry reg = Registry , individuals = nubOrd (individuals reg) } where - nubByPrefix = foldr (\n acc -> if any (\x -> nsPrefix x == nsPrefix n) acc then acc else n : acc) [] + -- Only exact repeats collapse: a prefix bound to two different URIs must reach the linter. + nubByPrefix = foldr (\n acc -> if n `elem` acc then acc else n : acc) [] data PropertyDef = PropertyDef { propName :: Name @@ -461,31 +462,51 @@ formatConditional p c = "if " ++ formatFOL p ++ " then " ++ formatFOL c +-- | The comparison with its operands swapped: @gt a b@ is @lt b a@. Equality, disequality and +-- anything that is not an ordering operator are symmetric and come back unchanged. This is +-- the one definition every emitter and prover helper shares. +flipOp :: String -> String +flipOp "gt" = "lt" +flipOp "gte" = "lte" +flipOp "lt" = "gt" +flipOp "lte" = "gte" +flipOp o = o + +-- | Every direct sub-formula of a formula (one level). Shared by the walks below. +subformulas :: FOL -> [FOL] +subformulas f = case f of + And a b -> [a, b] + Or a b -> [a, b] + Implies a b -> [a, b] + Iff a b -> [a, b] + Not a -> [a] + ForAll _ b -> [b] + Exists _ b -> [b] + TypedForAll _ _ b -> [b] + TypedExists _ _ b -> [b] + _ -> [] + +-- | The formula and all of its descendants. +universeFOL :: FOL -> [FOL] +universeFOL f = f : concatMap universeFOL (subformulas f) + +-- | The four ordering operators, minus any the ontology declares as a relation. A declared +-- relation called @gt@ is a relation, not a comparison. +orderingOps :: Registry -> [String] +orderingOps reg = filter (`notElem` map relName (relations reg)) ["gt", "gte", "lt", "lte"] + -- | Numeric bound literals @op(property, constant)@ in the axioms, normalised so the property --- is the left operand. Only the four ordering operators with numeric constants are collected. -numericBoundLiterals :: [FOL] -> [(String, String)] -numericBoundLiterals = nubOrd . concatMap go +-- is the left operand. Only the four ordering operators with numeric constants are collected, +-- and an operator the ontology declares as a relation is not one of them. +numericBoundLiterals :: Registry -> [(String, String)] +numericBoundLiterals reg = nubOrd (concatMap literals (concatMap universeFOL (axioms reg))) where - ordOps = ["gt", "gte", "lt", "lte"] - go f = case f of + ordOps = orderingOps reg + literals f = case f of Predicate op [Var _, Constant c] | op `elem` ordOps, numeric c -> [(op, c)] Predicate op [Constant c, Var _] | op `elem` ordOps, numeric c -> [(flipOp op, c)] - And a b -> go a ++ go b - Or a b -> go a ++ go b - Implies a b -> go a ++ go b - Iff a b -> go a ++ go b - Not a -> go a - ForAll _ b -> go b - Exists _ b -> go b - TypedForAll _ _ b -> go b - TypedExists _ _ b -> go b _ -> [] numeric c = (readMaybe c :: Maybe Double) /= Nothing - flipOp "gt" = "lt" - flipOp "gte" = "lte" - flipOp "lt" = "gt" - flipOp "lte" = "gte" - flipOp o = o -- | Pairs of numeric bound literals that no real number satisfies together (a lower bound above -- an upper bound, or meeting it with a strict side). Provers without arithmetic (the native @@ -493,9 +514,9 @@ numericBoundLiterals = nubOrd . concatMap go -- @forall t. not (op1(t, a) and op2(t, b))@ for each pair. These are valid over the reals and -- hence over the integers too, so they never make a satisfiable theory unsatisfiable; they are -- incomplete (integer gaps such as gt 5 and lt 6 are not detected). -disjointBoundPairs :: [FOL] -> [((String, String), (String, String))] -disjointBoundPairs axs = - let lits = numericBoundLiterals axs +disjointBoundPairs :: Registry -> [((String, String), (String, String))] +disjointBoundPairs reg = + let lits = numericBoundLiterals reg num c = maybe 0 id (readMaybe c :: Maybe Double) lowers = [ l | l@(op, _) <- lits, op `elem` ["gt", "gte"] ] uppers = [ u | u@(op, _) <- lits, op `elem` ["lt", "lte"] ] @@ -507,18 +528,5 @@ disjointBoundPairs axs = -- | Whether any axiom compares values with an ordering operator (gt, gte, lt, lte). A declared -- relation that shares one of those names is a relation, not a comparison. usesOrderingComparison :: Registry -> Bool -usesOrderingComparison reg = any go (axioms reg) - where - ordOps = filter (`notElem` map relName (relations reg)) ["gt", "gte", "lt", "lte"] - go f = case f of - Predicate op _ -> op `elem` ordOps - And a b -> go a || go b - Or a b -> go a || go b - Implies a b -> go a || go b - Iff a b -> go a || go b - Not a -> go a - ForAll _ b -> go b - Exists _ b -> go b - TypedForAll _ _ b -> go b - TypedExists _ _ b -> go b - _ -> False +usesOrderingComparison reg = + or [ op `elem` orderingOps reg | ax <- axioms reg, Predicate op _ <- universeFOL ax ] diff --git a/src/Prover/Resolution.hs b/src/Prover/Resolution.hs index f9437e7..85aa427 100644 --- a/src/Prover/Resolution.hs +++ b/src/Prover/Resolution.hs @@ -1,3 +1,4 @@ +{-# OPTIONS_GHC -fno-omit-yields #-} {-# LANGUAGE DeriveGeneric #-} module Prover.Resolution ( ClauseId(..) diff --git a/src/Prover/Tableau.hs b/src/Prover/Tableau.hs index d8ca031..8b374f3 100644 --- a/src/Prover/Tableau.hs +++ b/src/Prover/Tableau.hs @@ -1,3 +1,4 @@ +{-# OPTIONS_GHC -fno-omit-yields #-} {-# LANGUAGE DeriveGeneric #-} module Prover.Tableau ( -- * Core Types diff --git a/src/Prover/Unification.hs b/src/Prover/Unification.hs index 5892c70..a6cc2e1 100644 --- a/src/Prover/Unification.hs +++ b/src/Prover/Unification.hs @@ -1,3 +1,4 @@ +{-# OPTIONS_GHC -fno-omit-yields #-} module Prover.Unification ( Subst , emptySubst diff --git a/src/REPL.hs b/src/REPL.hs index 1ca6857..8d555e6 100644 --- a/src/REPL.hs +++ b/src/REPL.hs @@ -9,16 +9,18 @@ import Data.List (isPrefixOf, intercalate) import OntoLogic import Parser (parseRegistry) import Linter (lintRegistry) -import Loader (loadRegistryWithImports) +import Loader (loadRegistryWithImports, ontologicVersion) import IR (compileRegistry) import IR.CNF (formatCNFTheory) import IR.Clausify (clausifyTheory) import Targets (lookupTarget, targets, targetName, targetEmit, defaultEmitOptions, EmitOptions(..)) import Solver ( checkConsistencyWith + , usesSmtTheory , proveSubsumptionWith , findUnsatConceptsWith , untranslatedAxioms + , partialVerdict , arithmeticCaveat , Prover(..) , parseProver @@ -38,11 +40,18 @@ data REPLState = REPLState initialREPLState :: REPLState initialREPLState = REPLState emptyRegistry Nothing AutoProver defaultEmitOptions +-- | Centre a title inside the 60-column banner box. +bannerLine :: String -> String +bannerLine t = "║" ++ replicate l ' ' ++ t ++ replicate r ' ' ++ "║" + where pad = max 0 (60 - length t) + l = pad `div` 2 + r = pad - l + -- | Main interactive REPL loop runREPL :: IO () runREPL = do putStrLn "╔════════════════════════════════════════════════════════════╗" - putStrLn "║ OntoLogic Interactive REPL v1.0 ║" + putStrLn (bannerLine ("OntoLogic Interactive REPL v" ++ ontologicVersion)) putStrLn "║ Type ':help' for commands or enter DSL expressions ║" putStrLn "╚════════════════════════════════════════════════════════════╝" loop initialREPLState @@ -126,12 +135,12 @@ evalREPLCommand state input in return (state, "Compiled ModelIR:\n" ++ show ir) | input `elem` [":solve", ":check"] = do - let skipped = untranslatedAxioms (replRegistry state) - warning + skipped <- skippedAxioms state + let warning | null skipped = "" - | otherwise = "⚠️ " ++ show (length skipped) ++ " axiom(s) were not sent to the solver:\n" - ++ unlines [ " - " ++ show ax ++ " (" ++ why ++ ")" | (ax, why) <- skipped ] - res <- checkConsistencyWith (replProver state) (replRegistry state) + | otherwise = "\n⚠️ " ++ show (length skipped) ++ " axiom(s) were not sent to the solver:\n" + ++ init (unlines [ " - " ++ show ax ++ " (" ++ why ++ ")" | (ax, why) <- skipped ]) + res <- partialVerdict (length skipped) <$> checkConsistencyWith (replProver state) (replRegistry state) let consistency = case res of Sat model -> "✅ SMT Satisfiable (SAT) via " ++ proverName (replProver state) ++ " — Consistent Model Found:\n" ++ model Unsat -> "❌ SMT Unsatisfiable (UNSAT) via " ++ proverName (replProver state) ++ " — Logical Contradiction Detected!" @@ -147,27 +156,37 @@ evalREPLCommand state input (Sat _, _) -> caveatLine state (_, Right []) -> caveatLine state _ -> return "" - return (state, warning ++ consistency ++ "\n" ++ coherence ++ note) + return (state, consistency ++ warning ++ "\n" ++ coherence ++ note) | input `elem` [":explain", ":unsat-core", ":explain-unsat"] = do - res <- explainUnsatWith (replProver state) (replRegistry state) - case res of - Left err -> return (state, "❌ SMT Explanation Error:\n" ++ err) - Right explanation -> - if null (unsatCoreNames explanation) - then do - note <- caveatLine state - return (state, "✅ SMT Satisfiable (SAT) — No contradictory axioms or unsat cores detected." ++ note) - else return (state, unlines - [ "❌ SMT Unsatisfiable (UNSAT) — Minimal Unsat Core Identified:" - , " Core Assertions: " ++ unwords (unsatCoreNames explanation) - , "" - , "Conflicting Axioms Trace:" - , unlines (unsatCoreDetails explanation) - ]) + -- A core exists only for an unsatisfiable theory: decide that first, from the verdict, + -- so a satisfiable answer is never mistaken for an empty core. + skipped <- skippedAxioms state + verdict <- partialVerdict (length skipped) <$> checkConsistencyWith (replProver state) (replRegistry state) + case verdict of + Sat _ -> do + note <- caveatLine state + return (state, "✅ SMT Satisfiable (SAT) — No contradictory axioms or unsat cores detected." ++ note) + Unknown out -> return (state, "⚠️ SMT Solver Result Inconclusive, so no unsat core can be explained: " ++ out) + SolverError err -> return (state, "❌ SMT Solver Error:\n" ++ err) + Unsat -> do + res <- explainUnsatWith (replProver state) (replRegistry state) + case res of + Left err -> return (state, "❌ SMT Explanation Error:\n" ++ err) + Right explanation -> + if null (unsatCoreNames explanation) + then return (state, "❌ SMT Unsatisfiable (UNSAT) — the solver returned an empty unsat core, so no single axiom is blamed.") + else return (state, unlines + [ "❌ SMT Unsatisfiable (UNSAT) — Minimal Unsat Core Identified:" + , " Core Assertions: " ++ unwords (unsatCoreNames explanation) + , "" + , "Conflicting Axioms Trace:" + , unlines (unsatCoreDetails explanation) + ]) | input `elem` [":model", ":inspect-model"] = do - res <- checkConsistencyWith (replProver state) (replRegistry state) + skipped <- skippedAxioms state + res <- partialVerdict (length skipped) <$> checkConsistencyWith (replProver state) (replRegistry state) case res of Sat _ -> do note <- caveatLine state @@ -182,9 +201,13 @@ evalREPLCommand state input let args = words (trim (drop 7 input)) case args of [child, parent] -> do + skippedN <- length <$> skippedAxioms state res <- proveSubsumptionWith (replProver state) (replRegistry state) child parent case res of Subsumed -> return (state, "✅ Theorem Proved via " ++ proverName (replProver state) ++ ": '" ++ child ++ "' ⊑ '" ++ parent ++ "' (Every instance of " ++ child ++ " is necessarily a " ++ parent ++ ").") + NotSubsumed _ | skippedN > 0 -> + return (state, "⚠️ Theorem unknown via " ++ proverName (replProver state) ++ ": a counterexample exists for the axioms that were checked, but " + ++ show skippedN ++ " axiom(s) could not be checked, so '" ++ child ++ "' ⊑ '" ++ parent ++ "' is neither proved nor disproved. Run :solve to list them.") NotSubsumed model -> do note <- caveatLine state return (state, "❌ Theorem Disproved via " ++ proverName (replProver state) ++ ": '" ++ child ++ "' is NOT subsumed by '" ++ parent ++ "'. Counterexample model:\n" ++ model ++ note) @@ -197,7 +220,9 @@ evalREPLCommand state input Left err -> return (state, "❌ SMT Solver Error:\n" ++ err) Right [] -> do note <- caveatLine state - return (state, "✅ All concepts are satisfiable (0 empty concepts) via " ++ proverName (replProver state) ++ "." ++ note) + skipped <- skippedAxioms state + let partial = if null skipped then "" else "\n⚠️ " ++ show (length skipped) ++ " axiom(s) were not sent to the solver, so this covers the checked axioms only. Run :solve to list them." + return (state, "✅ All concepts are satisfiable (0 empty concepts) via " ++ proverName (replProver state) ++ "." ++ note ++ partial) Right unsatList -> return (state, "❌ Unsatisfiable / Contradictory Concepts Found via " ++ proverName (replProver state) ++ ":\n" ++ unlines (map (" - " ++) unsatList)) | input == ":clear" = @@ -231,6 +256,9 @@ evalREPLCommand state input Nothing -> return (state, "❌ Unknown emit target: " ++ target ++ ". Valid targets: " ++ intercalate ", " (map targetName targets)) Just tgt -> return (state, concatMap snd (targetEmit tgt (replEmitOptions state) (replRegistry state))) + | ":" `isPrefixOf` input = + return (state, "❌ Unknown command: " ++ head (words input) ++ ". Type :help for commands.") + | otherwise = do -- Try parsing as DSL S-expression case parse parseRegistry "<repl>" (T.pack input) of @@ -241,6 +269,12 @@ evalREPLCommand state input lintMsg = if null errs then "" else "\n⚠️ Lint warning: " ++ head errs in return (state { replRegistry = merged }, "Added to registry." ++ lintMsg) +-- | Axioms the current prover's theory leaves out (empty for backends that do not use SMT-LIB). +skippedAxioms :: REPLState -> IO [(FOL, String)] +skippedAxioms state = do + smtRoute <- usesSmtTheory (replProver state) + return (if smtRoute then untranslatedAxioms (replRegistry state) else []) + -- | Extra line for an all-clear answer from a prover without arithmetic; empty when none applies. caveatLine :: REPLState -> IO String caveatLine state = maybe "" ("\n⚠️ " ++) <$> arithmeticCaveat (replProver state) (replRegistry state) diff --git a/src/Solver.hs b/src/Solver.hs index cc65481..86f9fc3 100644 --- a/src/Solver.hs +++ b/src/Solver.hs @@ -1,12 +1,22 @@ module Solver ( SolverResult(..) , solverExitCode + , partialVerdict + , partialMessage , SubsumptionResult(..) , Prover(..) , SolverOptions(..) , defaultSolverOptions , RunFailure(..) , classifyOutput + , classifyConsistencyOutput + , classifyVampireOutput + , vampireArguments + , parseUnsatCore + , usesEquality + , usesSmtTheory + , clampTimeoutSeconds + , defaultSolveTimeoutSeconds , runBinary , wallClockGraceSeconds , parseProver @@ -49,7 +59,7 @@ import IR.CNF (CNFTerm(..), Literal(..), Clause(..), CNFTheory(..), formatClause import IR.Clausify (clausifyTheory) import Prover.Tableau (proveTableauClauses, defaultTableauConfig, TableauConfig(..), TableauResult(..), formatCounterModel) import Prover.Resolution (proveResolution, defaultConfig, ProverConfig(..), ProverResult(..), ProverStatus(..), DerivationNode(..), Derivation(..), ClauseId(..)) -import Emitters.SMT (emitSMTDeclarations) +import Emitters.SMT (emitSMTDeclarationsUnbounded) import Emitters.TPTP (emitTPTP, emitTPTPSubsumption, emitTPTPCoherence) import FOLTheory (buildTheory, buildNamedTheory, theoryText, theorySkipped, conceptPred) import System.Process (readProcessWithExitCode) @@ -58,9 +68,9 @@ import System.Directory (findExecutable) import System.IO.Error (isDoesNotExistError) import Control.Exception (try, IOException) import System.Timeout (timeout) -import Data.List (isPrefixOf, isInfixOf) +import Data.List (isPrefixOf, isInfixOf, nub) import Data.Char (toLower) -import Data.Maybe (isNothing) +import Data.Maybe (isNothing, isJust) import qualified Data.Map as Map -- | Supported automated theorem prover backends @@ -78,10 +88,28 @@ data SolverOptions = SolverOptions , optMemoryLimitMb :: Maybe Int } deriving (Show, Eq) --- | Default solver options: no explicit timeout or memory limit (defer to prover defaults) +-- | Time limit applied when the caller gives none (CLI without -T, REPL, LSP). +defaultSolveTimeoutSeconds :: Int +defaultSolveTimeoutSeconds = 60 + +-- | Longest limit honoured: one year. Larger values are clamped so the microsecond +-- arithmetic for 'System.Timeout' and the millisecond one for cvc5 and the native +-- prover cannot overflow. +maxTimeoutSeconds :: Int +maxTimeoutSeconds = 31536000 + +-- | Bring a requested limit into the range every backend handles. +clampTimeoutSeconds :: Int -> Int +clampTimeoutSeconds = max 1 . min maxTimeoutSeconds + +-- | The limit in force for a set of options: the clamped request, or the default. +effectiveTimeout :: SolverOptions -> Int +effectiveTimeout = maybe defaultSolveTimeoutSeconds clampTimeoutSeconds . optTimeoutSeconds + +-- | Default solver options: a 60 second time limit and no memory limit. defaultSolverOptions :: SolverOptions defaultSolverOptions = SolverOptions - { optTimeoutSeconds = Nothing + { optTimeoutSeconds = Just defaultSolveTimeoutSeconds , optMemoryLimitMb = Nothing } @@ -117,17 +145,102 @@ trimStart = dropWhile (`elem` (" \t\r\n" :: String)) -- | Decide whether a finished solver run produced a usable answer. -- A leading sat/unsat/unknown verdict is kept even with a non-zero exit (e.g. get-model after unsat). +-- Fail closed: an SMT-LIB @(error@ line other than a get-model or get-unsat-core refusal that +-- follows a verdict, and any Vampire parse failure, make the whole run a solver failure. The +-- solver carries on after a rejected assertion and answers for the rest, so such a verdict +-- would be about a different theory than the one that was sent. classifyOutput :: String -> ExitCode -> String -> String -> Either RunFailure String classifyOutput label code out err -- cvc5 --tlimit: "cvc5 interrupted by timeout." on stderr, empty stdout, SIGABRT exit. | "interrupted by timeout" `isInfixOf` err = Right (timedOutOutput label) - | any (`isPrefixOf` trimmed) ["sat", "unsat", "unknown"] = Right out + | Just why <- vampireFailure out = Left (SolverFailed (label ++ " could not read the problem: " ++ why ++ "\n" ++ trimStart (out ++ err))) + | Left bad <- smtVerdicts out = Left (SolverFailed (label ++ " reported an error: " ++ bad ++ "\n" ++ trimStart (out ++ err))) | any (`isInfixOf` out) ["SZS status", "SZS output"] = Right out - | any (`elem` ["sat", "unsat", "unknown"]) (map trimStart (lines out)) = Right out - | code == ExitSuccess && not ("(error" `isInfixOf` out) = Right out + | any (`elem` ["sat", "unsat", "unknown", "timeout"]) (map trim (lines out)) = Right out + | code == ExitSuccess = Right out | otherwise = Left (SolverFailed (label ++ " failed (" ++ show code ++ "):\n" ++ trimStart (out ++ err))) + +trim :: String -> String +trim = reverse . trimStart . reverse . trimStart + +-- | A verdict line of an SMT-LIB solver. +data Verdict = VSat | VUnsat | VUnknown + deriving (Eq, Show) + +-- | The verdict lines of SMT-LIB output, in order. Left carries the first error line that is +-- not a refusal of get-model or get-unsat-core right after a verdict. z3 prints @timeout@ +-- when -T expires; that is an unknown. +smtVerdicts :: String -> Either String [Verdict] +smtVerdicts = go False . map trim . lines where - trimmed = trimStart out + go _ [] = Right [] + go afterVerdict (l : ls) + | Just v <- verdictOf l = (v :) <$> go True ls + | "(error" `isPrefixOf` l = + if afterVerdict && benignRefusal l then go True ls else Left l + | otherwise = go False ls + verdictOf "sat" = Just VSat + verdictOf "unsat" = Just VUnsat + verdictOf "unknown" = Just VUnknown + verdictOf "timeout" = Just VUnknown + verdictOf _ = Nothing + benignRefusal l = any (`isInfixOf` map toLower l) + [ "model is not available", "cannot get model" + , "unsat core is not available", "cannot get unsat core" ] + +-- | Exactly one verdict, or the reason there is not one. +singleVerdict :: String -> Either String Verdict +singleVerdict out = case smtVerdicts out of + Left bad -> Left ("solver reported an error: " ++ bad) + Right [v] -> Right v + Right [] -> Left "solver printed no sat/unsat/unknown verdict" + Right vs -> Left ("solver printed " ++ show (length vs) ++ " verdicts where one was expected") + +-- | Why Vampire could not use the problem, if it could not: a TPTP or SMT-LIB parse failure. +vampireFailure :: String -> Maybe String +vampireFailure out = case [ l | l <- map plain (lines out), bad l ] of + (l : _) -> Just l + [] -> Nothing + where + plain = dropWhile (`elem` ("% \t\r" :: String)) + bad l = any (`isPrefixOf` l) ["Failed with", "User error", "parse error", "Parsing Error", "Parse error"] + +-- | The SZS status words of Vampire output. +szsStatuses :: String -> [String] +szsStatuses out = + [ w | l <- lines out + , let l' = dropWhile (`elem` ("% \t" :: String)) l + , "SZS status " `isPrefixOf` l' + , (w : _) <- [words (drop (length ("SZS status " :: String)) l')] ] + +-- | Vampire's single SZS status, falling back to a plain SMT-LIB verdict (smtcomp mode). +vampireStatus :: String -> Either String String +vampireStatus out + | Just why <- vampireFailure out = Left ("Vampire could not read the problem: " ++ why ++ "\n" ++ out) + | otherwise = case nub (szsStatuses out) of + [w] -> Right w + [] -> case singleVerdict out of + Right VSat -> Right "Satisfiable" + Right VUnsat -> Right "Unsatisfiable" + Right VUnknown -> Right "Unknown" + Left e -> Left ("Vampire gave no usable answer (" ++ e ++ "):\n" ++ out) + ws -> Left ("Vampire printed conflicting statuses " ++ unwords ws ++ ":\n" ++ out) + +-- | Statuses that mean the search ended without an answer. +vampireUnknownStatus :: String -> Bool +vampireUnknownStatus w = w `elem` ["Timeout", "GaveUp", "ResourceOut", "MemoryOut", "Incomplete", "Unknown", "Stopped"] + +-- | Verdict on a consistency problem sent to Vampire. Only a status that says the axioms +-- are satisfiable or unsatisfiable is an answer; give-up statuses are unknown, anything +-- else is an error. +classifyVampireOutput :: String -> SolverResult +classifyVampireOutput out = case vampireStatus out of + Left e -> SolverError e + Right w + | w `elem` ["Satisfiable", "CounterSatisfiable"] -> Sat out + | w `elem` ["Unsatisfiable", "ContradictoryAxioms"] -> Unsat + | vampireUnknownStatus w -> Unknown out + | otherwise -> SolverError ("Vampire answered with unexpected status " ++ w ++ ":\n" ++ out) -- | A run that hit its time limit, phrased as an SMT "unknown" verdict so every -- caller classifies it as Unknown (exit 2) rather than a solver failure. @@ -144,9 +257,7 @@ runBinary :: SolverOptions -> String -> FilePath -> [String] -> String -> IO (Ei runBinary opts label exe args smtInput = do -- readProcessWithExitCode terminates the child when interrupted by timeout. let run = try (readProcessWithExitCode exe args smtInput) :: IO (Either IOException (ExitCode, String, String)) - limited <- case optTimeoutSeconds opts of - Nothing -> Just <$> run - Just s -> timeout ((s + wallClockGraceSeconds) * 1000000) run + limited <- timeout ((effectiveTimeout opts + wallClockGraceSeconds) * 1000000) run return $ case limited of Nothing -> Right (timedOutOutput label) Just result -> case result of @@ -159,7 +270,7 @@ runBinary opts label exe args smtInput = do runProverRawWithOptions :: SolverOptions -> Prover -> String -> IO (Either RunFailure String) runProverRawWithOptions opts Z3 = let extraArgs = - [ "-T:" ++ show s | Just s <- [optTimeoutSeconds opts] ] ++ + [ "-T:" ++ show (effectiveTimeout opts) ] ++ [ "-memory:" ++ show m | Just m <- [optMemoryLimitMb opts] ] in runBinary opts "Z3" "z3" (["-in"] ++ extraArgs) -- --incremental: the coherence check uses push/pop, which cvc5 refuses without it. @@ -167,18 +278,11 @@ runProverRawWithOptions opts Z3 = -- on satisfiable quantified input without finite model finding. runProverRawWithOptions opts CVC5 = let extraArgs = - [ "--tlimit=" ++ show (s * 1000) | Just s <- [optTimeoutSeconds opts] ] + [ "--tlimit=" ++ show (effectiveTimeout opts * 1000) ] -- Options must precede the "-" stdin marker: cvc5 ignores anything after it. in runBinary opts "CVC5" "cvc5" (["--lang=smt2", "--produce-models", "--produce-unsat-cores", "--incremental", "--finite-model-find"] ++ extraArgs ++ ["-"]) runProverRawWithOptions opts Vampire = \input -> - let isSmt = any (`isPrefixOf` trimStart input) [";", "(", "set-logic"] - timeoutSec = maybe "10" show (optTimeoutSeconds opts) - args = if isSmt - then ["--input_syntax", "smtlib2", "--mode", "smtcomp"] ++ - maybe [] (\s -> ["-t", show s]) (optTimeoutSeconds opts) ++ - ["/dev/stdin"] - else ["--mode", "casc", "-t", timeoutSec, "/dev/stdin"] - in runBinary opts "Vampire" "vampire" args input + runBinary opts "Vampire" "vampire" (vampireArguments opts input) input runProverRawWithOptions _ NativeProver = \_ -> return (Left (SolverFailed "NativeProver operates on in-memory AST/CNF. Use checkConsistency, proveSubsumption, or findUnsatConcepts.")) runProverRawWithOptions opts AutoProver = \smtInput -> tryEach smtInput [Z3, CVC5, Vampire] @@ -191,6 +295,17 @@ runProverRawWithOptions opts AutoProver = \smtInput -> tryEach smtInput [Z3, CVC Left (NotInstalled _) -> tryEach smtIn ps other -> return other +-- | Command line for Vampire. The input syntax is always named: left to "auto", Vampire +-- retries a TPTP problem it could not parse as SMT-LIB on the already drained stdin, +-- and the empty second read has been answered as satisfiable. +vampireArguments :: SolverOptions -> String -> [String] +vampireArguments opts input + | isSmt = ["--input_syntax", "smtlib2", "--mode", "smtcomp", "-t", secs, "/dev/stdin"] + | otherwise = ["--input_syntax", "tptp", "--mode", "casc", "-t", secs, "/dev/stdin"] + where + isSmt = any (`isPrefixOf` trimStart input) [";", "(", "set-logic"] + secs = show (effectiveTimeout opts) + -- | Run raw SMT-LIB2 or TPTP code through the selected prover backend runProverRaw :: Prover -> String -> IO (Either RunFailure String) runProverRaw = runProverRawWithOptions defaultSolverOptions @@ -216,6 +331,17 @@ solverExitCode Unsat = ExitFailure 1 solverExitCode (SolverError _) = ExitFailure 1 solverExitCode (Unknown _) = ExitFailure 2 +-- | Message for a satisfiable answer that covers only part of the theory. +partialMessage :: Int -> String +partialMessage n = "The axioms that were checked are consistent, but " ++ show n + ++ " axiom(s) could not be checked, so consistency of the whole ontology is unknown." + +-- | A satisfiable answer is a verdict on the axioms actually sent. When @n@ axioms were not +-- sent, SAT becomes unknown; UNSAT stands (a contradictory subset contradicts the whole). +partialVerdict :: Int -> SolverResult -> SolverResult +partialVerdict n (Sat _) | n > 0 = Unknown (partialMessage n) +partialVerdict _ r = r + -- | The most severe of several exit codes: failure beats unknown beats success. worst :: [ExitCode] -> ExitCode worst codes @@ -273,18 +399,17 @@ runVampireTPTP = runProver Vampire -- | Check consistency and satisfiability of the entire ontology registry with specified solver options and prover checkConsistencyWithOptions :: SolverOptions -> Prover -> Registry -> IO SolverResult -checkConsistencyWithOptions opts NativeProver reg = do - let cnf = clausifyTheory reg - cfg = case optTimeoutSeconds opts of - Just s -> defaultConfig { cfgTimeoutMs = Just (s * 1000) } - Nothing -> defaultConfig - res <- proveResolution cfg cnf - return $ case prStatus res of - Proved -> Unsat - Saturated -> Sat "Satisfiable (clausal theory saturated without refutation)" - Timeout -> Unknown "Native resolution prover timed out" - StepLimit -> Unknown "Native resolution prover step limit exceeded" - ClauseLimit -> Unknown "Native resolution prover clause limit exceeded" +checkConsistencyWithOptions opts NativeProver reg + | usesEquality reg = return (Unknown nativeEqualityMessage) + | otherwise = do + let cnf = clausifyTheory reg + res <- proveResolution (nativeConfig opts) cnf + return $ case prStatus res of + Proved -> Unsat + Saturated -> Sat "Satisfiable (clausal theory saturated without refutation)" + Timeout -> Unknown "Native resolution prover timed out" + StepLimit -> Unknown "Native resolution prover step limit exceeded" + ClauseLimit -> Unknown "Native resolution prover clause limit exceeded" checkConsistencyWithOptions opts AutoProver reg = do let smtCode = emitSMTForConsistency reg res <- runProverRawWithOptions opts AutoProver smtCode @@ -299,11 +424,7 @@ checkConsistencyWithOptions opts Vampire reg = do res <- runProverWithOptions opts Vampire tptp return $ case res of Left err -> SolverError err - Right out - | any (`isInfixOf` out) ["SZS status Satisfiable", "SZS status CounterSatisfiable"] || any (== "sat") (map trimStart (lines out)) -> Sat out - | "SZS status Unsatisfiable" `isInfixOf` out || any (== "unsat") (map trimStart (lines out)) -> Unsat - | "SZS status Timeout" `isInfixOf` out || any (== "unknown") (map trimStart (lines out)) -> Unknown out - | otherwise -> SolverError out + Right out -> classifyVampireOutput out checkConsistencyWithOptions opts p reg = do let smtCode = emitSMTForConsistency reg res <- runProverWithOptions opts p smtCode @@ -315,14 +436,14 @@ checkConsistencyWithOptions opts p reg = do checkConsistencyWith :: Prover -> Registry -> IO SolverResult checkConsistencyWith = checkConsistencyWithOptions defaultSolverOptions +-- | Verdict on an SMT-LIB consistency run. Exactly one verdict line is an answer; an error +-- line, no verdict, or several verdicts is a solver error, never SAT. classifyConsistencyOutput :: String -> SolverResult -classifyConsistencyOutput out = - let trimmed = trimStart out - in if "sat" `isPrefixOf` trimmed || any (== "sat") (map trimStart (lines out)) - then Sat out - else if "unsat" `isPrefixOf` trimmed || any (== "unsat") (map trimStart (lines out)) - then Unsat - else Unknown out +classifyConsistencyOutput out = case singleVerdict out of + Left e -> SolverError (e ++ ":\n" ++ out) + Right VSat -> Sat out + Right VUnsat -> Unsat + Right VUnknown -> Unknown out -- | Check consistency and satisfiability using automatic prover selection checkConsistency :: Registry -> IO SolverResult @@ -332,6 +453,7 @@ checkConsistency = checkConsistencyWith AutoProver proveSubsumptionWithOptions :: SolverOptions -> Prover -> Registry -> String -> String -> IO SubsumptionResult proveSubsumptionWithOptions opts p reg child parent | not (null unknown) = return (ProofError ("Unknown concept(s): " ++ unwords unknown)) + | p == NativeProver && usesEquality reg = return (ProofError nativeEqualityMessage) | p == NativeProver = do let cnf = clausifyTheory reg skConst = TConst ("c_subsumption_test_" ++ child) @@ -340,16 +462,12 @@ proveSubsumptionWithOptions opts p reg child parent , Clause (Set.singleton (Neg parent [skConst])) ] queryCnf = CNFTheory (Set.union (Set.fromList negGoalClauses) (getClauses cnf)) - cfg = case optTimeoutSeconds opts of - Just s -> defaultConfig { cfgTimeoutMs = Just (s * 1000) } - Nothing -> defaultConfig + cfg = nativeConfig opts res <- proveResolution cfg queryCnf case prStatus res of Proved -> return Subsumed Saturated -> do - let tabCfg = case optTimeoutSeconds opts of - Just s -> defaultTableauConfig { tcMaxDepth = 10, tcMaxSteps = 200, tcTimeoutMs = Just (s * 1000) } - Nothing -> defaultTableauConfig { tcMaxDepth = 10, tcMaxSteps = 200 } + let tabCfg = defaultTableauConfig { tcMaxDepth = 10, tcMaxSteps = 200, tcTimeoutMs = Just (effectiveTimeout opts * 1000) } tabRes <- proveTableauClauses tabCfg negGoalClauses return $ case trCounterModel tabRes of Just m -> NotSubsumed (formatCounterModel m) @@ -362,11 +480,13 @@ proveSubsumptionWithOptions opts p reg child parent res <- runProverWithOptions opts Vampire tptp return $ case res of Left err -> ProofError err - Right out - | "SZS status Theorem" `isInfixOf` out -> Subsumed - | any (`isInfixOf` out) ["SZS status CounterSatisfiable", "SZS status Satisfiable"] -> NotSubsumed out - | "SZS status Timeout" `isInfixOf` out -> ProofError "Vampire proof timed out" - | otherwise -> ProofError out + Right out -> case vampireStatus out of + Left e -> ProofError e + Right w + | w == "Theorem" -> Subsumed + | w `elem` ["CounterSatisfiable", "Satisfiable"] -> NotSubsumed out + | vampireUnknownStatus w -> ProofError ("Vampire could not decide (" ++ w ++ ")") + | otherwise -> ProofError ("Vampire answered with unexpected status " ++ w ++ ":\n" ++ out) | p == AutoProver = do let smt = "(set-logic ALL)\n(declare-sort Entity 0)\n" ++ theoryText (buildTheory reg) ++ "; Negated goal: some " ++ child ++ " is not a " ++ parent ++ "\n" ++ @@ -374,10 +494,7 @@ proveSubsumptionWithOptions opts p reg child parent "(check-sat)\n(get-model)\n" res <- runProverRawWithOptions opts AutoProver smt case res of - Right out - | "unsat" `isPrefixOf` trimStart out || any (== "unsat") (map trimStart (lines out)) -> return Subsumed - | "sat" `isPrefixOf` trimStart out || any (== "sat") (map trimStart (lines out)) -> return (NotSubsumed out) - | otherwise -> return (ProofError out) + Right out -> return (subsumptionFromSmt out) Left (NotInstalled _) -> -- Zero-dependency fallback to NativeProver! proveSubsumptionWithOptions opts NativeProver reg child parent @@ -390,13 +507,19 @@ proveSubsumptionWithOptions opts p reg child parent res <- runProverWithOptions opts p smt return $ case res of Left err -> ProofError err - Right out - | "unsat" `isPrefixOf` trimStart out || any (== "unsat") (map trimStart (lines out)) -> Subsumed - | "sat" `isPrefixOf` trimStart out || any (== "sat") (map trimStart (lines out)) -> NotSubsumed out - | otherwise -> ProofError out + Right out -> subsumptionFromSmt out where unknown = filter (`notElem` map fst (concepts reg)) [child, parent] +-- | Subsumption verdict from an SMT-LIB run of the negated goal: unsat proves it, sat refutes +-- it, anything else is an error. +subsumptionFromSmt :: String -> SubsumptionResult +subsumptionFromSmt out = case singleVerdict out of + Left e -> ProofError (e ++ ":\n" ++ out) + Right VUnsat -> Subsumed + Right VSat -> NotSubsumed out + Right VUnknown -> ProofError ("Solver answered unknown:\n" ++ out) + -- | Prove whether ConceptA is subsumed by ConceptB (A ⊑ B) with specified prover proveSubsumptionWith :: Prover -> Registry -> String -> String -> IO SubsumptionResult proveSubsumptionWith = proveSubsumptionWithOptions defaultSolverOptions @@ -407,13 +530,13 @@ proveSubsumption = proveSubsumptionWith AutoProver -- | Find all unsatisfiable concepts in one solver run with specified options; Left if the solver could not decide. findUnsatConceptsWithOptions :: SolverOptions -> Prover -> Registry -> IO (Either String [String]) +findUnsatConceptsWithOptions _ NativeProver reg + | usesEquality reg = return (Left nativeEqualityMessage) findUnsatConceptsWithOptions opts NativeProver reg = do let names = map compClassName (irClasses (compileRegistry reg)) cnf = clausifyTheory reg baseClauses = getClauses cnf - cfg = case optTimeoutSeconds opts of - Just s -> defaultConfig { cfgTimeoutMs = Just (s * 1000) } - Nothing -> defaultConfig + cfg = nativeConfig opts checkConcept c = do let skConst = TConst ("c_coherence_test_" ++ c) conceptClause = Clause (Set.singleton (Pos c [skConst])) @@ -425,10 +548,13 @@ findUnsatConceptsWithOptions opts NativeProver reg = do Timeout -> Left ("Native prover timeout for concept " ++ c) StepLimit -> Left ("Native prover step limit exceeded for concept " ++ c) ClauseLimit -> Left ("Native prover clause limit exceeded for concept " ++ c) - results <- mapM checkConcept names - return $ case sequence results of - Left err -> Left err - Right matches -> Right [ c | Just c <- matches ] + -- One deadline for the whole sweep: the limit bounds the call, not each concept. + swept <- timeout (effectiveTimeout opts * 1000000) (mapM checkConcept names) + return $ case swept of + Nothing -> Left "Native prover timed out checking concept coherence" + Just results -> case sequence results of + Left err -> Left err + Right matches -> Right [ c | Just c <- matches ] findUnsatConceptsWithOptions opts AutoProver reg = do let names = map compClassName (irClasses (compileRegistry reg)) check c = "(push 1)\n(assert (exists ((x Entity)) (" ++ conceptPred c ++ " x)))\n(check-sat)\n(pop 1)\n" @@ -447,10 +573,12 @@ findUnsatConceptsWithOptions opts Vampire reg = do res <- runProverWithOptions opts Vampire tptp return $ case res of Left err -> Left err - Right out - | "SZS status Unsatisfiable" `isInfixOf` out -> Right (Just c) - | any (`isInfixOf` out) ["SZS status Satisfiable", "SZS status CounterSatisfiable"] -> Right Nothing - | otherwise -> Left ("Vampire check inconclusive for concept " ++ c ++ ":\n" ++ out) + Right out -> case vampireStatus out of + Right w + | w `elem` ["Unsatisfiable", "ContradictoryAxioms"] -> Right (Just c) + | w `elem` ["Satisfiable", "CounterSatisfiable"] -> Right Nothing + Right w -> Left ("Vampire check inconclusive for concept " ++ c ++ " (" ++ w ++ "):\n" ++ out) + Left e -> Left ("Vampire check failed for concept " ++ c ++ ": " ++ e) results <- mapM checkConcept names return $ case sequence results of Left err -> Left err @@ -469,13 +597,14 @@ findUnsatConceptsWith :: Prover -> Registry -> IO (Either String [String]) findUnsatConceptsWith = findUnsatConceptsWithOptions defaultSolverOptions parseUnsatConceptVerdicts :: [String] -> String -> Either String [String] -parseUnsatConceptVerdicts names out = - let verdicts = filter (`elem` ["sat", "unsat", "unknown"]) (map (filter (`notElem` (" \t\r" :: String))) (lines out)) - in if length verdicts /= length names - then Left ("Expected " ++ show (length names) ++ " solver answers, got " ++ show (length verdicts) ++ ":\n" ++ out) - else case [ n | (n, "unknown") <- zip names verdicts ] of - [] -> Right [ n | (n, "unsat") <- zip names verdicts ] - unknowns -> Left ("Solver answered unknown for: " ++ unwords unknowns) +parseUnsatConceptVerdicts names out = case smtVerdicts out of + Left bad -> Left ("Solver reported an error, so the per-concept answers cannot be trusted: " ++ bad ++ "\n" ++ out) + Right verdicts + | length verdicts /= length names -> + Left ("Expected " ++ show (length names) ++ " solver answers, got " ++ show (length verdicts) ++ ":\n" ++ out) + | otherwise -> case [ n | (n, VUnknown) <- zip names verdicts ] of + [] -> Right [ n | (n, VUnsat) <- zip names verdicts ] + unknowns -> Left ("Solver answered unknown for: " ++ unwords unknowns) -- | Find all unsatisfiable (logically empty/contradictory) concepts using AutoProver findUnsatConcepts :: Registry -> IO (Either String [String]) @@ -494,7 +623,7 @@ emitSMTBase :: Registry -> String emitSMTBase reg = "; SMT-LIB2 Base Declarations generated by OntoLogic Solver\n" ++ "(set-logic ALL)\n\n" ++ - emitSMTDeclarations reg + emitSMTDeclarationsUnbounded reg -- | Extract model valuation s-expression from a Sat result extractModel :: SolverResult -> Maybe String @@ -522,26 +651,13 @@ data UnsatExplanation = UnsatExplanation explainUnsat :: Registry -> IO (Either String UnsatExplanation) explainUnsat = explainUnsatWith AutoProver --- | Parse S-expression list of unsat core identifiers from solver output (supporting both Z3 and CVC5) -extractCoreNames :: String -> [String] -extractCoreNames out = - let ws = words out - in case dropWhile (/= "unsat") ws of - ("unsat" : rest) -> - let body = unwords rest - inside = takeWhile (/= ')') (dropWhile (/= '(') body) - in words (filter (`notElem` ("()" :: String)) inside) - _ -> case [ l | l <- lines (trimStart out), "(" `isPrefixOf` l && not ("(error" `isPrefixOf` l) ] of - (c:_) -> words (filter (`notElem` ("():\r\n" :: String)) c) - [] -> [] - -- | Run SMT with :produce-unsat-cores to identify conflicting axioms with specified options and prover explainUnsatWithOptions :: SolverOptions -> Prover -> Registry -> IO (Either String UnsatExplanation) +explainUnsatWithOptions _ NativeProver reg + | usesEquality reg = return (Left nativeEqualityMessage) explainUnsatWithOptions opts NativeProver reg = do let cnf = clausifyTheory reg - cfg = case optTimeoutSeconds opts of - Just s -> defaultConfig { cfgTimeoutMs = Just (s * 1000) } - Nothing -> defaultConfig + cfg = nativeConfig opts res <- proveResolution cfg cnf return $ case prStatus res of Proved -> @@ -552,13 +668,13 @@ explainUnsatWithOptions opts NativeProver reg = do details = [ formatClause (dnClause node) | node <- inputNodes ] in Right (UnsatExplanation names details) Nothing -> Right (UnsatExplanation [] []) - Saturated -> Right (UnsatExplanation [] []) + Saturated -> Left "The theory is satisfiable (saturated without refutation), so there is no unsat core." status -> Left ("Native prover explanation inconclusive: " ++ show status) explainUnsatWithOptions opts AutoProver reg = do let (smtCode, nameMap) = emitSMTForUnsatCore reg res <- runProverRawWithOptions opts AutoProver smtCode case res of - Right out -> parseUnsatCoreOutput out nameMap + Right out -> return (parseUnsatCore out nameMap) Left (NotInstalled _) -> -- Zero-dependency fallback to NativeProver! explainUnsatWithOptions opts NativeProver reg @@ -568,26 +684,80 @@ explainUnsatWithOptions opts p reg = do res <- runProverWithOptions opts p smtCode case res of Left err -> return (Left err) - Right out -> parseUnsatCoreOutput out nameMap + Right out -> return (parseUnsatCore out nameMap) -- | Run SMT with :produce-unsat-cores to identify conflicting axioms with specified prover explainUnsatWith :: Prover -> Registry -> IO (Either String UnsatExplanation) explainUnsatWith = explainUnsatWithOptions defaultSolverOptions -parseUnsatCoreOutput :: String -> Map.Map String String -> IO (Either String UnsatExplanation) -parseUnsatCoreOutput out nameMap = - let trimmed = trimStart out - in if "sat" `isPrefixOf` trimmed - then return (Right (UnsatExplanation [] [])) - else - let names = extractCoreNames out - details = [ Map.findWithDefault n n nameMap | n <- names ] - in if null names && "unsat" `isPrefixOf` trimmed - then return (Right (UnsatExplanation [] [])) - else if null names - then return (Left ("Could not extract unsat core from solver output:\n" ++ out)) - else return (Right (UnsatExplanation names details)) +-- | Read the answer to @(check-sat) (get-unsat-core)@. Only an @unsat@ verdict followed by the +-- core list is a core: a @sat@ answer (with z3's "core is not available" refusal) means the +-- named theory is satisfiable and has no core, and is not an empty core. +parseUnsatCore :: String -> Map.Map String String -> Either String UnsatExplanation +parseUnsatCore out nameMap = case singleVerdict out of + Left e -> Left ("Could not extract unsat core: " ++ e ++ ":\n" ++ out) + Right VSat -> Left "The solver found the theory satisfiable, so there is no unsat core." + Right VUnknown -> Left ("The solver answered unknown, so there is no unsat core:\n" ++ out) + Right VUnsat -> + let afterVerdict = unlines (drop 1 (dropWhile ((/= "unsat") . trim) (lines out))) + in case balancedGroup (dropWhile (/= '(') afterVerdict) of + Nothing -> Left ("Could not extract unsat core from solver output:\n" ++ out) + Just inside -> + let names = words (map (\c -> if c `elem` ("()" :: String) then ' ' else c) inside) + in Right (UnsatExplanation names [ Map.findWithDefault n n nameMap | n <- names ]) + +-- | The text inside the first balanced parenthesis group at the start of a string. +balancedGroup :: String -> Maybe String +balancedGroup ('(' : rest) = go (1 :: Int) rest "" + where + go _ [] _ = Nothing + go d (c : cs) acc + | c == '(' = go (d + 1) cs (c : acc) + | c == ')' = if d == 1 then Just (reverse acc) else go (d - 1) cs (c : acc) + | otherwise = go d cs (c : acc) +balancedGroup _ = Nothing -- | Emit SMT-LIB2 with :produce-unsat-cores and named assertions for tracking contradictions emitSMTForUnsatCore :: Registry -> (String, Map.Map String String) emitSMTForUnsatCore = buildNamedTheory + +-- | Native prover settings for a set of options. +nativeConfig :: SolverOptions -> ProverConfig +nativeConfig opts = defaultConfig { cfgTimeoutMs = Just (effectiveTimeout opts * 1000) } + +-- | The native resolution prover has no equality reasoning: it reads @=@ as an ordinary +-- predicate, so it can saturate (and report SAT) on theories that equality refutes, and +-- it mis-clausifies property comparisons. Any theory that uses equality is unknown to it. +usesEquality :: Registry -> Bool +usesEquality = any hasEq . axioms + where + hasEq f = case f of + Eq _ _ -> True + Predicate n _ -> n `elem` ["eq", "ne", "="] + ForAll _ b -> hasEq b + Exists _ b -> hasEq b + TypedForAll _ _ b -> hasEq b + TypedExists _ _ b -> hasEq b + And a b -> hasEq a || hasEq b + Or a b -> hasEq a || hasEq b + Implies a b -> hasEq a || hasEq b + Iff a b -> hasEq a || hasEq b + Not a -> hasEq a + Top -> False + Bottom -> False + +nativeEqualityMessage :: String +nativeEqualityMessage = + "The native prover has no equality reasoning and this theory uses equality (=, eq or ne), " ++ + "so it cannot answer. Use z3, cvc5 or vampire." + +-- | Whether a prover answers from the SMT-LIB theory ('untranslatedAxioms' describes what that +-- theory leaves out). Vampire reads the TPTP encoding and the native prover the clausal one, +-- so the SMT notice does not apply to them. 'AutoProver' sends SMT-LIB to whichever external +-- solver it finds, and uses the native prover only when there is none. +usesSmtTheory :: Prover -> IO Bool +usesSmtTheory Z3 = return True +usesSmtTheory CVC5 = return True +usesSmtTheory Vampire = return False +usesSmtTheory NativeProver = return False +usesSmtTheory AutoProver = any isJust <$> mapM findExecutable ["z3", "cvc5", "vampire"] diff --git a/test/DocSamplesSpec.hs b/test/DocSamplesSpec.hs new file mode 100644 index 0000000..ce9c934 --- /dev/null +++ b/test/DocSamplesSpec.hs @@ -0,0 +1,79 @@ +{-# LANGUAGE OverloadedStrings #-} +-- | Every complete ontology sample in the user-facing docs must parse. +module DocSamplesSpec (spec) where + +import Test.Hspec +import Text.Megaparsec (parse, errorBundlePretty) +import System.Directory (listDirectory, doesFileExist) +import System.FilePath ((</>), takeExtension) +import Data.Char (isSpace, toLower) +import Data.List (isPrefixOf, isInfixOf, sort) +import qualified Data.Text as T +import qualified Data.Text.Encoding as TE +import qualified Data.Text.Encoding.Error as TEE +import qualified Data.ByteString as BS + +import Parser (parseRegistry) + +data Sample = Sample { sFile :: FilePath, sStart :: Int, sEnd :: Int, sBody :: String } + +-- | Samples known broken until the docs stream fixes them: (file, line). +knownBroken :: [(FilePath, Int)] +knownBroken = [] + +docFiles :: IO [FilePath] +docFiles = do + guide <- sort . filter ((== ".md") . takeExtension) <$> listDirectory "docs/user-guide" + let fs = ["README.md", "docs/using.md", "docs/standard-library.md"] ++ map ("docs/user-guide" </>) guide + filterM' doesFileExist fs + where filterM' p = fmap concat . mapM (\x -> (\b -> [x | b]) <$> p x) + +-- | Fenced blocks as (language tag, first body line number, body lines). +fences :: [String] -> [(String, Int, [String])] +fences = go 1 + where + go _ [] = [] + go n (l:ls) + | "```" `isPrefixOf` dropWhile isSpace l = + let lang = map toLower (trim (drop 3 (dropWhile isSpace l))) + (body, rest) = break (isPrefixOf "```" . dropWhile isSpace) ls + in (lang, n, body) : go (n + length body + 2) (drop 1 rest) + | otherwise = go (n + 1) ls + +trim :: String -> String +trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace + +firstCode :: [String] -> String +firstCode ls = case filter (\l -> not (null (trim l)) && not (";" `isPrefixOf` trim l)) ls of + (l:_) -> trim l + [] -> "" + +looksLikeLogic :: String -> [String] -> Bool +looksLikeLogic lang body + | lang `elem` ["lisp", "logic", "ontologic", "scheme", "clojure"] = True + | null lang = "(" `isPrefixOf` firstCode body && any (`isInfixOf` unwords body) ["(def-", "(namespace", "(import", "(axiom"] + | otherwise = False + +isTemplate :: [String] -> Bool +isTemplate body = any (\l -> "[" `isInfixOf` l || "..." `isInfixOf` l) body + +samplesOf :: FilePath -> IO [Sample] +samplesOf f = do + ls <- lines . T.unpack . TE.decodeUtf8With TEE.lenientDecode <$> BS.readFile f + return [ Sample f n (n + length body) (unlines body) + | (lang, n, body) <- fences ls, looksLikeLogic lang body, not (isTemplate body) ] + +spec :: Spec +spec = describe "Documentation samples" $ do + samples <- runIO (docFiles >>= fmap concat . mapM samplesOf) + it "finds samples to check" $ length samples `shouldSatisfy` (> 10) + mapM_ check samples + where + check s = + let label = sFile s ++ ":" ++ show (sStart s) + broken = any (\(f, n) -> f == sFile s && n >= sStart s - 1 && n <= sEnd s + 1) knownBroken + result = parse parseRegistry label (T.pack (sBody s)) + in it ("parses " ++ label) $ case result of + Right _ -> return () + Left err | broken -> pendingWith ("known broken until docs are fixed: " ++ label) + | otherwise -> expectationFailure (errorBundlePretty err) diff --git a/test/DomainExamplesSpec.hs b/test/DomainExamplesSpec.hs index 26dac9c..c15f463 100644 --- a/test/DomainExamplesSpec.hs +++ b/test/DomainExamplesSpec.hs @@ -95,7 +95,7 @@ spec = describe "Domain examples (data-driven fixtures)" $ do hasConflict <- runIO (doesFileExist conflict) if hasConflict - then it "conflict fixture is inconsistent (UNSAT)" $ do + then it "conflict fixture is flagged (UNSAT or an empty concept)" $ do mp <- pickSmtProver case mp of Nothing -> pendingWith "neither z3 nor cvc5 installed in PATH" @@ -105,8 +105,13 @@ spec = describe "Domain examples (data-driven fixtures)" $ do Left err -> expectationFailure (conflict ++ ": failed to load: " ++ err) Right reg -> do res <- checkConsistencyWithOptions domainOpts prover reg - case res of - Unsat -> return () - _ -> expectationFailure (conflict ++ ": expected UNSAT but got " ++ show res) - else it "conflict fixture is inconsistent (UNSAT)" $ + -- A bound that contradicts another for every instance of a concept makes that + -- concept empty; it is a contradiction of the whole theory only if an instance + -- is asserted. Either outcome flags the conflict; SAT with no empty concept does not. + coh <- findUnsatConceptsWithOptions domainOpts prover reg + case (res, coh) of + (Unsat, _) -> return () + (_, Right (_:_)) -> return () + _ -> expectationFailure (conflict ++ ": expected UNSAT or an empty concept but got " ++ show (res, coh)) + else it "conflict fixture is flagged (UNSAT or an empty concept)" $ pendingWith ("no " ++ conflict) diff --git a/test/EmitterParitySpec.hs b/test/EmitterParitySpec.hs new file mode 100644 index 0000000..e7a1a05 --- /dev/null +++ b/test/EmitterParitySpec.hs @@ -0,0 +1,252 @@ +-- | v1.8.4 emitter parity: a rule in the source is either enforced by the generated code or +-- reported as unmapped. It never becomes a check that cannot fail and never disappears +-- without a warning. Where python3 (with pydantic), rustc, go or javac are installed the +-- generated output is compiled and RUN against valid and invalid instances. +module EmitterParitySpec (spec) where + +import Test.Hspec +import Control.Monad (forM_, when) +import Data.List (isInfixOf, intercalate) +import Data.Text (pack) +import System.Directory (createDirectoryIfMissing, removeDirectoryRecursive, doesDirectoryExist, findExecutable, getHomeDirectory) +import System.Exit (ExitCode(..)) +import System.FilePath ((</>)) +import System.Process (readProcessWithExitCode) +import Text.Megaparsec (parse, errorBundlePretty) +import OntoLogic +import Parser (parseRegistry) +import IR +import Emitters.Python (emitPython) +import Emitters.Java (emitJava) +import Emitters.Rust (emitRust) +import Emitters.Go (emitGo) +import Emitters.TypeScript (emitTypeScript) +import Emitters.Shacl (emitShacl) +import Emitters.TPTP (emitTPTP) + +load :: String -> Registry +load src = either (error . errorBundlePretty) id (parse parseRegistry "t" (pack src)) + +-- | Five rules that used to vanish or turn into a vacuous check. +paritySrc :: String +paritySrc = unlines + [ "(def-concept Account)" + , "(def-concept LockedAccount Account)" + , "(def-property state Account String)" + , "(def-property enabled Account Boolean)" + , "(def-property balance Account Integer)" + , "(def-property is_active Account Boolean)" + , "(def-property pressure Account Integer)" + , "(forall (a) (implies (LockedAccount a) (eq state \"locked\")))" + , "(forall (a) (implies (LockedAccount a) (eq enabled False)))" + , "(forall (a) (implies (Account a) (gte balanse 0)))" + , "(forall (a) (implies (Account a) (ne balance 13)))" + , "(forall (a) (implies (and (Account a) (eq is_active True)) (gt pressure 1)))" + ] + +-- | Expected verdict (True = valid) for the eight probe instances used by every runner: +-- A1 balance 13, A2 plain valid, A3 active with pressure 1, A4 active with pressure 2, +-- L1 locked account with state "open", L2 locked with enabled true, L3 valid locked, +-- L4 valid locked but active with pressure 0 (an inherited conditional). +expectedVerdicts :: [Bool] +expectedVerdicts = [False, True, False, True, False, False, True, False] + +workDir :: String -> IO FilePath +workDir name = do + let d = ".test-tmp" </> ("parity_" ++ name) + exists <- doesDirectoryExist d + when exists (removeDirectoryRecursive d) + createDirectoryIfMissing True d + return d + +verdicts :: String -> [Bool] +verdicts out = [ l == "ok" | l <- lines out, l `elem` ["ok", "err"] ] + +spec :: Spec +spec = describe "Emitter parity (v1.8.4)" $ do + let reg = load paritySrc + unmappedText = concatMap formatFOL (irUnmappedAxioms (compileRegistry reg)) + + describe "unmapped reporting" $ do + it "lists string equality, Boolean equality, ne and the undeclared-property bound" $ do + unmappedText `shouldSatisfy` ("state" `isInfixOf`) + unmappedText `shouldSatisfy` ("enabled" `isInfixOf`) + unmappedText `shouldSatisfy` ("balanse" `isInfixOf`) + unmappedText `shouldSatisfy` ("ne(balance" `isInfixOf`) + + it "does not list a numeric bound on a declared numeric property" $ do + let ok = load "(def-concept A)\n(def-property n A Integer)\n(forall (a) (implies (A a) (gte n 0)))" + irUnmappedAxioms (compileRegistry ok) `shouldBe` [] + + describe "no translator falls back to true" $ do + it "Python/Java/Go/Rust/TypeScript never emit a constant-true premise" $ do + emitPython reg `shouldSatisfy` (not . ("if True and" `isInfixOf`) ) + forM_ (emitJava reg) $ \(_, c) -> c `shouldSatisfy` (not . ("if (true)" `isInfixOf`)) + emitGo reg `shouldSatisfy` (not . ("if (true) &&" `isInfixOf`)) + emitRust reg `shouldSatisfy` (not . ("if (true) &&" `isInfixOf`)) + emitTypeScript reg `shouldSatisfy` (not . ("if (true)" `isInfixOf`)) + + it "enforces the eq conditional in TypeScript and SHACL" $ do + emitTypeScript reg `shouldSatisfy` ("data.is_active === true" `isInfixOf`) + emitTypeScript reg `shouldSatisfy` ("data.state === \"locked\"" `isInfixOf`) + emitTypeScript reg `shouldSatisfy` ("data.balance !== 13" `isInfixOf`) + let shacl = emitShacl reg + shacl `shouldSatisfy` ("sh:path ont:is_active" `isInfixOf`) + shacl `shouldSatisfy` ("sh:hasValue true" `isInfixOf`) + shacl `shouldSatisfy` ("sh:hasValue \"locked\"" `isInfixOf`) + + it "keeps an untranslatable conditional out of the generated code" $ do + let r = load $ unlines + [ "(def-concept P)", "(def-property a P Integer)" + , "(forall (p) (implies (and (P p) (eq typo_flag True)) (gt a 1)))" ] + emitPython r `shouldSatisfy` (not . ("typo_flag" `isInfixOf`)) + irUnmappedAxioms (compileRegistry r) `shouldSatisfy` (not . null) + + describe "a declared relation named like a comparison" $ do + let relReg = load $ unlines + [ "(def-concept Widget)" + , "(def-relation gt Widget Widget)" + , "(def-relation lt Widget Widget)" + , "(forall (w) (gt w 5))" + , "(exists (w) (lt w 3))" ] + it "is not treated as arithmetic" $ do + numericBoundLiterals relReg `shouldBe` [] + disjointBoundPairs relReg `shouldBe` [] + emitTPTP relReg `shouldSatisfy` (not . ("cmp_" `isInfixOf`)) + emitTPTP relReg `shouldSatisfy` ("rel_gt(" `isInfixOf`) + it "still treats undeclared gt/lt as arithmetic" $ do + let a = load "(def-concept W)\n(def-property n W Integer)\n(forall (w) (implies (W w) (gt n 5)))\n(forall (w) (implies (W w) (lt n 3)))" + disjointBoundPairs a `shouldSatisfy` (not . null) + + describe "generated code, executed" $ do + it "Python (pydantic) rejects exactly the invalid instances" $ do + py <- findExecutable "python3" + case py of + Nothing -> pendingWith "python3 not installed" + Just p -> do + (probe, _, _) <- readProcessWithExitCode p ["-c", "import pydantic"] "" + if probe /= ExitSuccess then pendingWith "pydantic not installed" else do + d <- workDir "python" + writeFile (d </> "models.py") (emitPython reg) + writeFile (d </> "run.py") $ unlines + [ "from models import *" + , "def t(f):" + , " try:" + , " f(); print('ok')" + , " except Exception:" + , " print('err')" + , "A = dict(state='s', enabled=True, balance=1, is_active=False, pressure=0)" + , "t(lambda: Account(**{**A, 'balance': 13}))" + , "t(lambda: Account(**A))" + , "t(lambda: Account(**{**A, 'is_active': True, 'pressure': 1}))" + , "t(lambda: Account(**{**A, 'is_active': True, 'pressure': 2}))" + , "t(lambda: LockedAccount(**{**A, 'state': 'open', 'enabled': False}))" + , "t(lambda: LockedAccount(**{**A, 'state': 'locked', 'enabled': True}))" + , "t(lambda: LockedAccount(**{**A, 'state': 'locked', 'enabled': False}))" + , "t(lambda: LockedAccount(**{**A, 'state': 'locked', 'enabled': False, 'is_active': True, 'pressure': 0}))" + ] + (ec, out, err) <- readProcessWithExitCode p ["-c", "import sys; sys.path.insert(0, '" ++ d ++ "'); exec(open('" ++ (d </> "run.py") ++ "').read())"] "" + (ec, err) `shouldBe` (ExitSuccess, "") + verdicts out `shouldBe` expectedVerdicts + + it "Rust compiles and rejects exactly the invalid instances" $ do + rc <- findExecutable "rustc" + case rc of + Nothing -> pendingWith "rustc not installed" + Just r -> do + d <- workDir "rust" + let acct s e b a p = "Account { state: \"" ++ s ++ "\".to_string(), enabled: " ++ e ++ ", balance: " ++ show (b :: Int) ++ ", is_active: " ++ a ++ ", pressure: " ++ show (p :: Int) ++ " }" + locked s e a p = "LockedAccount { base: " ++ acct s e 1 a p ++ " }" + line v = " println!(\"{}\", if (" ++ v ++ ").validate().is_ok() { \"ok\" } else { \"err\" });" + mainFn = unlines $ ["fn main() {"] ++ map line + [ acct "s" "true" 13 "false" 0, acct "s" "true" 1 "false" 0 + , acct "s" "true" 1 "true" 1, acct "s" "true" 1 "true" 2 + , locked "open" "false" "false" 0, locked "locked" "true" "false" 0 + , locked "locked" "false" "false" 0, locked "locked" "false" "true" 0 + ] ++ ["}"] + writeFile (d </> "main.rs") (emitRust reg ++ "\n" ++ mainFn) + (ec, _, err) <- readProcessWithExitCode r [d </> "main.rs", "-o", d </> "prog"] "" + (ec, takeWhile (/= '\n') (if ec == ExitSuccess then "" else err), err) `shouldBe` (ExitSuccess, "", "") + (_, out, _) <- readProcessWithExitCode (d </> "prog") [] "" + verdicts out `shouldBe` expectedVerdicts + + it "Go compiles and rejects exactly the invalid instances" $ do + gc <- findExecutable "go" + case gc of + Nothing -> pendingWith "go not installed" + Just g -> do + d <- workDir "go" + let code = unlines (map (\l -> if l == "package models" then "package main" else l) (lines (emitGo reg))) + acct s e b a p = "Account{State: \"" ++ s ++ "\", Enabled: " ++ e ++ ", Balance: " ++ show (b :: Int) ++ ", IsActive: " ++ a ++ ", Pressure: " ++ show (p :: Int) ++ "}" + locked s e a p = "LockedAccount{Account: " ++ acct s e 1 a p ++ "}" + line v = " if len((&" ++ v ++ ").Validate()) == 0 { println(\"ok\") } else { println(\"err\") }" + mainFn = unlines $ ["func main() {"] ++ map line + [ acct "s" "true" 13 "false" 0, acct "s" "true" 1 "false" 0 + , acct "s" "true" 1 "true" 1, acct "s" "true" 1 "true" 2 + , locked "open" "false" "false" 0, locked "locked" "true" "false" 0 + , locked "locked" "false" "false" 0, locked "locked" "false" "true" 0 + ] ++ ["}"] + writeFile (d </> "models.go") code + writeFile (d </> "main.go") ("package main\n\n" ++ mainFn) + (ec, out, err) <- readProcessWithExitCode g ["run", d </> "models.go", d </> "main.go"] "" + -- println writes to stderr + (ec, out) `shouldBe` (ExitSuccess, "") + verdicts err `shouldBe` expectedVerdicts + + it "Java compiles and rejects exactly the invalid instances" $ do + jc <- findExecutable "javac" + home <- getHomeDirectory + (_, jarOut, _) <- readProcessWithExitCode "find" [home </> ".gradle" </> "caches", "-name", "jakarta.validation-api-*.jar"] "" + case (jc, lines jarOut) of + (Nothing, _) -> pendingWith "javac not installed" + (_, []) -> pendingWith "jakarta.validation-api jar not found" + (Just javac, jar : _) -> do + d <- workDir "java" + forM_ (emitJava reg) $ \(n, c) -> writeFile (d </> n ++ ".java") c + let mk cls s e a p = "mk(new " ++ cls ++ "(), \"" ++ s ++ "\", " ++ e ++ ", 1, " ++ a ++ ", " ++ show (p :: Int) ++ ")" + cases = + [ "bal(" ++ mk "Account" "s" "true" "false" 0 ++ ", 13)" + , mk "Account" "s" "true" "false" 0 + , mk "Account" "s" "true" "true" 1 + , mk "Account" "s" "true" "true" 2 + , mk "LockedAccount" "open" "false" "false" 0 + , mk "LockedAccount" "locked" "true" "false" 0 + , mk "LockedAccount" "locked" "false" "false" 0 + , mk "LockedAccount" "locked" "false" "true" 0 + ] + mainSrc = unlines + [ "import ontologic.generated.*;" + , "import java.lang.reflect.Method;" + , "public class Main {" + , " static Account mk(Account a, String s, boolean e, int b, boolean act, int p) {" + , " a.setState(s); a.setEnabled(e); a.setBalance(b); a.setIs_active(act); a.setPressure(p); return a; }" + , " static Account bal(Account a, int b) { a.setBalance(b); return a; }" + , " static boolean valid(Object o) throws Exception {" + , " for (Method m : o.getClass().getMethods())" + , " if (m.getName().startsWith(\"isValid\") && m.getParameterCount() == 0 && !((Boolean) m.invoke(o))) return false;" + , " return true; }" + , " public static void main(String[] x) throws Exception {" + , " Object[] all = new Object[] { " ++ intercalate ", " cases ++ " };" + , " for (Object o : all) System.out.println(valid(o) ? \"ok\" : \"err\");" + , " }" + , "}" + ] + writeFile (d </> "Main.java") mainSrc + let srcs = [ d </> n ++ ".java" | (n, _) <- emitJava reg ] ++ [d </> "Main.java"] + (ec, _, err) <- readProcessWithExitCode javac (["-cp", jar, "-d", d] ++ srcs) "" + (ec, err) `shouldBe` (ExitSuccess, "") + (_, out, _) <- readProcessWithExitCode "java" ["-cp", d ++ ":" ++ jar, "-ea", "Main"] "" + verdicts out `shouldBe` expectedVerdicts + + describe "conditionals on inherited properties compile (shipped examples)" $ + forM_ ["examples/bfo_energy.logic", "examples/domain_systems_engineering.logic"] $ \path -> + it ("Rust output for " ++ path ++ " compiles") $ do + rc <- findExecutable "rustc" + case rc of + Nothing -> pendingWith "rustc not installed" + Just r -> do + src <- readFile path + d <- workDir "corpus_rust" + writeFile (d </> "models.rs") (emitRust (load src)) + (ec, _, err) <- readProcessWithExitCode r ["--crate-type", "lib", "-A", "warnings", d </> "models.rs", "--out-dir", d] "" + (ec, err) `shouldBe` (ExitSuccess, "") diff --git a/test/FailClosedSpec.hs b/test/FailClosedSpec.hs new file mode 100644 index 0000000..b2f570c --- /dev/null +++ b/test/FailClosedSpec.hs @@ -0,0 +1,233 @@ +module FailClosedSpec (spec) where + +import Test.Hspec +import OntoLogic +import Solver +import qualified Data.Map as Map +import Data.Either (isLeft) +import Data.List (isInfixOf) +import System.Directory (findExecutable) +import System.Exit (ExitCode(..)) +import Loader (loadRegistryWithImports) + +fixture :: String -> FilePath +fixture n = "test/fixtures/failclosed/" ++ n ++ ".logic" + +load :: String -> IO Registry +load n = do + r <- loadRegistryWithImports (fixture n) + either (\e -> fail ("fixture " ++ n ++ ": " ++ e)) return r + +withTool :: String -> IO () -> IO () +withTool exe act = do + found <- findExecutable exe + maybe (pendingWith (exe ++ " not installed")) (const act) found + +isSat :: SolverResult -> Bool +isSat (Sat _) = True +isSat _ = False + +isSolverError :: SolverResult -> Bool +isSolverError (SolverError _) = True +isSolverError _ = False + +isNotSubsumed :: SubsumptionResult -> Bool +isNotSubsumed (NotSubsumed _) = True +isNotSubsumed _ = False + +-- | Short solver budget so a hang fails the test instead of the suite. +quick :: SolverOptions +quick = defaultSolverOptions { optTimeoutSeconds = Just 20 } + +spec :: Spec +spec = describe "Fail-closed solver verdicts (v1.8.4)" $ do + + describe "SMT-LIB verdict parsing" $ do + it "treats an error line next to a sat verdict as a solver error" $ + classifyConsistencyOutput "sat\n(error \"line 5 column 3: bad\")\n" `shouldSatisfy` isSolverError + it "treats an error line before the verdict as a solver error" $ + classifyConsistencyOutput "(error \"line 5 column 3: bad\")\nsat\n" `shouldSatisfy` isSolverError + it "accepts the get-model refusal that follows unsat" $ + classifyConsistencyOutput "unsat\n(error \"line 5 column 10: model is not available\")\n" `shouldBe` Unsat + it "accepts the cvc5 get-model refusal that follows unsat" $ + classifyConsistencyOutput "unsat\n(error \"cannot get model unless after a SAT or UNKNOWN response.\")\n" `shouldBe` Unsat + it "never reads unsat as sat" $ + classifyConsistencyOutput "unsat\n" `shouldBe` Unsat + it "does not read a sat line after an unsat line as sat" $ + classifyConsistencyOutput "unsat\nsat\n" `shouldSatisfy` isSolverError + it "reports no verdict line as a solver error" $ do + classifyConsistencyOutput "" `shouldSatisfy` isSolverError + classifyConsistencyOutput "(model)\n" `shouldSatisfy` isSolverError + it "keeps unknown as unknown" $ + classifyConsistencyOutput "unknown\n" `shouldSatisfy` (\r -> case r of Unknown _ -> True; _ -> False) + it "keeps a model after sat" $ + classifyConsistencyOutput "sat\n(\n(define-fun a () Bool true)\n)\n" `shouldSatisfy` isSat + + describe "Vampire verdict parsing" $ do + it "maps GaveUp and ResourceOut to unknown" $ do + classifyVampireOutput "% SZS status GaveUp for stdin\n" `shouldSatisfy` isUnknown + classifyVampireOutput "% SZS status ResourceOut for stdin\n" `shouldSatisfy` isUnknown + classifyVampireOutput "% SZS status Timeout for stdin\n" `shouldSatisfy` isUnknown + it "maps Satisfiable and Unsatisfiable" $ do + classifyVampireOutput "% SZS status Satisfiable for stdin\n" `shouldSatisfy` isSat + classifyVampireOutput "% SZS status CounterSatisfiable for stdin\n" `shouldSatisfy` isSat + classifyVampireOutput "% SZS status Unsatisfiable for stdin\n" `shouldBe` Unsat + it "treats a TPTP parse failure as an error" $ do + classifyVampireOutput "% Running in auto input_syntax mode. Trying TPTP\n% Failed with\n% parse error\n% Trying SMTLIB2\nUser error: Unexpected end of list\n" `shouldSatisfy` isSolverError + classifyVampireOutput "parse error in \"/dev/stdin\", line 1: formula or term expected\n" `shouldSatisfy` isSolverError + it "treats a parse failure as an error even beside a sat line" $ + classifyVampireOutput "% Failed with\nsat\n" `shouldSatisfy` isSolverError + it "treats conflicting statuses and no status as an error" $ do + classifyVampireOutput "% SZS status Satisfiable\n% SZS status Unsatisfiable\n" `shouldSatisfy` isSolverError + classifyVampireOutput "" `shouldSatisfy` isSolverError + it "passes --input_syntax tptp on the TPTP route" $ do + let args = vampireArguments defaultSolverOptions "fof(a,axiom,p).\n" + args `shouldSatisfy` (\as -> ["--input_syntax", "tptp"] `isInfixOfList` as) + it "keeps smtlib2 syntax on the SMT-LIB route" $ do + let args = vampireArguments defaultSolverOptions "(set-logic ALL)\n" + args `shouldSatisfy` (\as -> ["--input_syntax", "smtlib2"] `isInfixOfList` as) + + describe "Unsat core parsing" $ do + let nm = Map.fromList [("n1", "first"), ("n2", "second")] + it "reads a one-line core" $ + parseUnsatCore "unsat\n(n1 n2)\n" nm `shouldBe` Right (UnsatExplanation ["n1", "n2"] ["first", "second"]) + it "reads a multi-line core" $ + fmap unsatCoreNames (parseUnsatCore "unsat\n(\nn1\nn2\n)\n" nm) `shouldBe` Right ["n1", "n2"] + it "ignores a parenthesised group that is not the core" $ + fmap unsatCoreNames (parseUnsatCore "unsat\n(n2)\n" nm) `shouldBe` Right ["n2"] + it "does not turn a satisfiable answer into an empty core" $ + parseUnsatCore "sat\n(error \"line 5: unsat core is not available\")\n" nm `shouldSatisfy` isLeft + it "rejects an error line" $ + parseUnsatCore "unsat\n(error \"line 5: boom\")\n(n1)\n" nm `shouldSatisfy` isLeft + it "reports an empty core as an unsat answer with no names" $ + parseUnsatCore "unsat\n()\n" nm `shouldBe` Right (UnsatExplanation [] []) + + describe "Time limits" $ do + it "defaults to 60 seconds" $ + optTimeoutSeconds defaultSolverOptions `shouldBe` Just 60 + it "clamps huge values instead of overflowing" $ do + clampTimeoutSeconds maxBound `shouldSatisfy` (\s -> s > 0 && s <= 31536000) + clampTimeoutSeconds 5 `shouldBe` 5 + it "does not expire a quick command under a huge limit" $ do + exe <- findExecutable "true" + case exe of + Nothing -> pendingWith "true not found" + Just _ -> do + r <- runBinary (defaultSolverOptions { optTimeoutSeconds = Just maxBound }) "true" "true" [] "" + r `shouldBe` Right "" + + describe "Solver route" $ do + it "uses the SMT theory only for SMT routes" $ do + usesSmtTheory Vampire `shouldReturn` False + usesSmtTheory NativeProver `shouldReturn` False + usesSmtTheory Z3 `shouldReturn` True + usesSmtTheory CVC5 `shouldReturn` True + + describe "partialVerdict: SAT on a partial check is unknown" $ do + it "turns SAT into unknown when axioms were not sent" $ do + partialVerdict 2 (Sat "m") `shouldSatisfy` isUnknown + solverExitCode (partialVerdict 2 (Sat "m")) `shouldBe` ExitFailure 2 + it "keeps SAT when nothing was skipped" $ + partialVerdict 0 (Sat "m") `shouldSatisfy` isSat + it "keeps UNSAT, errors and unknown unchanged" $ do + partialVerdict 3 Unsat `shouldBe` Unsat + partialVerdict 3 (SolverError "e") `shouldSatisfy` isSolverError + it "names the count in the message" $ + case partialVerdict 2 (Sat "m") of + Unknown msg -> msg `shouldSatisfy` ("2 axiom(s) could not be checked" `isInfixOf`) + _ -> expectationFailure "expected unknown" + + describe "z3 and cvc5 never drop a rejected assertion silently (D5)" $ do + let check name solver exe = it (name ++ " on " ++ exe) $ withTool exe $ do + mapM_ (\f -> do + reg <- load f + res <- checkConsistencyWithOptions quick solver reg + -- Either a non-SAT answer, or a SAT that comes with the not-sent notice. + (isSat res && null (untranslatedAxioms reg)) `shouldBe` False + ) ["smt_string_arg", "smt_arity"] + check "string constant and arity mismatch" Z3 "z3" + check "string constant and arity mismatch" CVC5 "cvc5" + it "rejects the ill-sorted axioms as not sent" $ do + r1 <- load "smt_string_arg" + r2 <- load "smt_arity" + length (untranslatedAxioms r1) `shouldSatisfy` (>= 1) + length (untranslatedAxioms r2) `shouldSatisfy` (>= 1) + it "accepts nullary function terms on z3 and cvc5 (04_function_terms)" $ do + reg <- load "04_function_terms" + withTool "z3" $ do + res <- checkConsistencyWithOptions quick Z3 reg + res `shouldSatisfy` isSat + findUnsatConceptsWithOptions quick Z3 reg `shouldReturn` Right [] + withTool "cvc5" $ do + res <- checkConsistencyWithOptions quick CVC5 reg + res `shouldSatisfy` isSat + + describe "Vampire never answers SAT after a TPTP parse failure (D6)" $ do + it "does not report SAT for any parse-failing probe" $ withTool "vampire" $ + mapM_ (\f -> do + reg <- load f + res <- checkConsistencyWithOptions quick Vampire reg + -- All four probes are UNSAT in truth; an error or unknown is acceptable, SAT is not. + res `shouldSatisfy` (not . isSat) + ) ["ind_unary_fact_vampire", "string_space_tptp", "odd_ident"] + it "does not report SAT or Disproved from a parse failure in the coherence check" $ withTool "vampire" $ do + reg <- load "odd_ident" + coh <- findUnsatConceptsWithOptions quick Vampire reg + coh `shouldSatisfy` (/= Right []) + it "does not answer a subsumption that holds with NotSubsumed" $ withTool "vampire" $ do + reg <- load "subs_ind" + res <- proveSubsumptionWithOptions quick Vampire reg "A" "B" + res `shouldSatisfy` (not . isNotSubsumed) + + describe "Native prover answers unknown when the theory uses equality (B2)" $ do + it "detects equality" $ do + reg <- load "eq_congruence" + usesEquality reg `shouldBe` True + regNo <- load "subs_ind" + usesEquality regNo `shouldBe` False + it "consistency" $ do + reg <- load "eq_congruence" + res <- checkConsistencyWithOptions quick NativeProver reg + res `shouldSatisfy` isUnknown + solverExitCode res `shouldBe` ExitFailure 2 + it "coherence" $ do + reg <- load "eq_congruence" + res <- findUnsatConceptsWithOptions quick NativeProver reg + res `shouldSatisfy` isLeft + it "subsumption never says NotSubsumed" $ do + reg <- load "subs_eq" + res <- proveSubsumptionWithOptions quick NativeProver reg "A" "B" + res `shouldSatisfy` (not . isNotSubsumed) + it "explanation is an error, not an empty core" $ do + reg <- load "eq_congruence" + res <- explainUnsatWithOptions quick NativeProver reg + res `shouldSatisfy` isLeft + it "keeps answering for equality-free theories" $ do + reg <- load "subs_ind" + res <- checkConsistencyWithOptions quick NativeProver reg + res `shouldSatisfy` isSat + + describe "Bounds are not asserted on the concept constant (D4, solver side)" $ do + it "the consistency SMT carries no property bound assertion" $ do + reg <- load "bounds_int_gap_universal" + emitSMTForConsistency reg `shouldSatisfy` (not . ("(assert (> (Tank_level Tank) 5))" `isInfixOf`)) + it "guarded bounds on disjoint subconcepts stay consistent and coherent" $ withTool "z3" $ do + reg <- load "guarded_int_gap" + res <- checkConsistencyWithOptions quick Z3 reg + res `shouldSatisfy` isSat + coh <- findUnsatConceptsWithOptions quick Z3 reg + coh `shouldBe` Right [] + it "an empty concept is not a global contradiction" $ withTool "z3" $ do + reg <- load "bounds_int_gap_universal" + res <- checkConsistencyWithOptions quick Z3 reg + res `shouldSatisfy` isSat + coh <- findUnsatConceptsWithOptions quick Z3 reg + coh `shouldBe` Right ["Tank"] + it "agrees on cvc5" $ withTool "cvc5" $ do + reg <- load "bounds_int_gap_universal" + res <- checkConsistencyWithOptions quick CVC5 reg + res `shouldSatisfy` isSat + where + isUnknown (Unknown _) = True + isUnknown _ = False + isInfixOfList needle hay = any (\i -> take (length needle) (drop i hay) == needle) [0 .. length hay] diff --git a/test/ImportSpec.hs b/test/ImportSpec.hs index ca21fd4..7745cf9 100644 --- a/test/ImportSpec.hs +++ b/test/ImportSpec.hs @@ -11,7 +11,8 @@ import qualified Data.Text.IO as TIO import OntoLogic import Parser (parseRegistry, parseFOL) -import Loader (loadRegistryWithImports, loadRegistryWithLibPaths) +import Loader (loadRegistryWithImports, loadRegistryWithLibPaths, loadRegistryWithOptions) +import Data.List (isInfixOf) import Linter (lintRegistry) import Emitters.Owl (emitOwl) @@ -181,3 +182,48 @@ spec = do writeFile (tmp </> "sub" </> "m.logic") "(import \"bfo_2020.logic\")\n" res <- withCurrentDirectory tmp (loadRegistryWithLibPaths [repo </> "ontologic-lib"] "sub/m.logic") either expectationFailure (\reg -> lookup "Shadow" (concepts reg) `shouldBe` Nothing) res + + describe "Import hardening (B7)" $ do + let setup name body = do + tmp <- (</> name) <$> getTemporaryDirectory + createDirectoryIfMissing True tmp + writeFile (tmp </> "secret.txt") "TOPSECRETLINE\n" + writeFile (tmp </> "ok.logic") "(def-concept Ok)\n" + writeFile (tmp </> "root.logic") body + return tmp + + it "refuses an absolute import path by default and does not echo file contents" $ do + tmp <- setup "ontologic-b7-abs" "" + writeFile (tmp </> "root.logic") ("(import \"" ++ tmp ++ "/ok.logic\")\n") + res <- loadRegistryWithImports (tmp </> "root.logic") + case res of + Left err -> err `shouldSatisfy` ("Absolute import paths are not allowed" `isInfixOf`) + Right _ -> expectationFailure "absolute import was accepted" + + it "accepts an absolute .logic import with the opt-in flag" $ do + tmp <- setup "ontologic-b7-abs-ok" "" + writeFile (tmp </> "root.logic") ("(import \"" ++ tmp ++ "/ok.logic\")\n") + res <- loadRegistryWithOptions True [] (tmp </> "root.logic") + either expectationFailure (\(reg, _) -> lookup "Ok" (concepts reg) `shouldBe` Just Nothing) res + + it "rejects a non-.logic import even with the opt-in flag, without leaking contents" $ do + tmp <- setup "ontologic-b7-ext" "" + writeFile (tmp </> "root.logic") ("(import \"" ++ tmp ++ "/secret.txt\")\n") + res <- loadRegistryWithOptions True [] (tmp </> "root.logic") + case res of + Left err -> do + err `shouldSatisfy` ("must name a .logic file" `isInfixOf`) + err `shouldSatisfy` (not . ("TOPSECRETLINE" `isInfixOf`)) + Right _ -> expectationFailure "non-.logic import was accepted" + + it "rejects a relative non-.logic import" $ do + tmp <- setup "ontologic-b7-rel" "(import \"secret.txt\")\n" + res <- loadRegistryWithImports (tmp </> "root.logic") + either (\e -> e `shouldSatisfy` ("must name a .logic file" `isInfixOf`)) (const (expectationFailure "accepted")) res + + it "still allows relative ../ imports" $ do + tmp <- setup "ontologic-b7-dots" "" + createDirectoryIfMissing True (tmp </> "sub") + writeFile (tmp </> "sub" </> "m.logic") "(import \"../ok.logic\")\n" + res <- loadRegistryWithImports (tmp </> "sub" </> "m.logic") + either expectationFailure (\reg -> lookup "Ok" (concepts reg) `shouldBe` Just Nothing) res diff --git a/test/IndustrialBenchmarkSpec.hs b/test/IndustrialBenchmarkSpec.hs index 6181a35..e844017 100644 --- a/test/IndustrialBenchmarkSpec.hs +++ b/test/IndustrialBenchmarkSpec.hs @@ -21,16 +21,38 @@ import Solver , proveSubsumptionWith , findUnsatConceptsWith , explainUnsatWith + , usesEquality ) +-- | The native prover has no equality reasoning and answers unknown for any theory that uses it +-- (v1.8.4). These suites test its taxonomy reasoning, so they load the ontology without the +-- axioms that use equality; the equality-bearing original is checked separately. +loadNoEquality :: FilePath -> IO (Either String Registry) +loadNoEquality path = fmap strip <$> loadRegistryWithImports path + where + strip reg = reg { axioms = [ a | a <- axioms reg, not (usesEquality reg { axioms = [a] }) ] } + spec :: Spec spec = describe "Industrial Ontology Stress & Verification Suite" $ do + describe "Native prover and equality" $ + mapM_ (\path -> it ("answers unknown for " ++ path ++ ", which uses equality") $ do + loadRes <- loadRegistryWithImports path + case loadRes of + Left err -> expectationFailure err + Right reg -> do + usesEquality reg `shouldBe` True + res <- checkConsistencyWith NativeProver reg + case res of + Unknown _ -> return () + _ -> expectationFailure $ "Expected Unknown, got: " ++ show res) + ["examples/bfo_manufacturing.logic", "examples/mqtt_ecosystem_unified.logic", "examples/domain_security_trust.logic"] + describe "BFO Manufacturing Domain Ontology (bfo_manufacturing.logic)" $ do let path = "examples/bfo_manufacturing.logic" it "proves ontology consistency (SAT) natively in milliseconds" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right reg -> do @@ -40,7 +62,7 @@ spec = describe "Industrial Ontology Stress & Verification Suite" $ do _ -> expectationFailure $ "Expected Sat, got: " ++ show res it "proves multi-level taxonomic subsumption (Robot <= Entity)" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right reg -> do @@ -49,7 +71,7 @@ spec = describe "Industrial Ontology Stress & Verification Suite" $ do res `shouldBe` Subsumed it "proves process subsumption (WeldingProcess <= Process)" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right reg -> do @@ -57,7 +79,7 @@ spec = describe "Industrial Ontology Stress & Verification Suite" $ do res `shouldBe` Subsumed it "disproves non-subsumption between disjoint BFO branches (Robot <= Process)" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right reg -> do @@ -67,7 +89,7 @@ spec = describe "Industrial Ontology Stress & Verification Suite" $ do _ -> expectationFailure $ "Expected NotSubsumed, got: " ++ show res it "verifies full concept coherence across all 21 concepts" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right reg -> do @@ -78,7 +100,7 @@ spec = describe "Industrial Ontology Stress & Verification Suite" $ do let path = "examples/mqtt_ecosystem_unified.logic" it "proves consistency (SAT) over large 100+ clause clausal theory" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right reg -> do @@ -88,7 +110,7 @@ spec = describe "Industrial Ontology Stress & Verification Suite" $ do _ -> expectationFailure $ "Expected Sat, got: " ++ show res it "proves taxonomic inheritance (Object <= Entity)" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right reg -> do @@ -96,7 +118,7 @@ spec = describe "Industrial Ontology Stress & Verification Suite" $ do res `shouldBe` Subsumed it "disproves subsumption across distinct branches (Process <= Continuant)" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right reg -> do @@ -109,7 +131,7 @@ spec = describe "Industrial Ontology Stress & Verification Suite" $ do let path = "examples/domain_security_trust.logic" it "proves consistency natively" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right reg -> do @@ -143,7 +165,7 @@ spec = describe "Industrial Ontology Stress & Verification Suite" $ do let path = "examples/bfo_manufacturing.logic" it "identifies injected contradictory concept as unsatisfiable" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right baseReg -> do @@ -162,7 +184,7 @@ spec = describe "Industrial Ontology Stress & Verification Suite" $ do unsatList `shouldBe` Right ["BrokenMachine"] it "detects full ontology UNSAT and extracts refutation core when instance is asserted" $ do - loadRes <- loadRegistryWithImports path + loadRes <- loadNoEquality path case loadRes of Left err -> expectationFailure err Right baseReg -> do diff --git a/test/JavaSpec.hs b/test/JavaSpec.hs index 91f6755..d8264af 100644 --- a/test/JavaSpec.hs +++ b/test/JavaSpec.hs @@ -178,7 +178,7 @@ spec = do case files of [("Controller", code)] -> do code `shouldContain` "@AssertTrue" - code `shouldContain` "public boolean isValidConstraint1()" + code `shouldContain` "public boolean isValidConstraint_Controller_1()" let tmpDir = "/tmp/javac_assert_test" createDirectoryIfMissing True tmpDir writeFile (tmpDir </> "Controller.java") code @@ -209,9 +209,9 @@ spec = do files = emitJava reg case files of [("Device", code)] -> do - code `shouldContain` "(this.power != null && this.power < 10)" - code `shouldContain` "!Objects.equals(this.mode, \"standby\")" - code `shouldContain` "(!\"False\".equalsIgnoreCase(String.valueOf(this.active)) && !Boolean.FALSE.equals(this.active))" + code `shouldContain` "(this.getPower() != null && this.getPower() < 10)" + code `shouldContain` "!Objects.equals(this.getMode(), \"standby\")" + code `shouldContain` "(!\"False\".equalsIgnoreCase(String.valueOf(this.getActive())) && !Boolean.FALSE.equals(this.getActive()))" _ -> expectationFailure "Expected single Device file" it "emits collection cardinalities and exclusive decimal bounds" $ do diff --git a/test/LSPSpec.hs b/test/LSPSpec.hs index 9604753..10a7932 100644 --- a/test/LSPSpec.hs +++ b/test/LSPSpec.hs @@ -7,7 +7,7 @@ import Parser (parseRegistry) import Text.Megaparsec (parse) import System.Timeout (timeout) import Control.Exception (evaluate) -import Data.Maybe (isJust) +import Data.Maybe (isJust, isNothing) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BC import qualified Data.Text as T @@ -15,7 +15,7 @@ import qualified Data.Text.Encoding as TE import qualified Data.Map.Strict as Map import Data.List (isInfixOf) import System.IO (openBinaryFile, hClose, IOMode(ReadMode)) -import System.Directory (getTemporaryDirectory, createDirectoryIfMissing) +import System.Directory (getTemporaryDirectory, createDirectoryIfMissing, findExecutable) import System.FilePath ((</>)) spec :: Spec @@ -192,6 +192,21 @@ spec = describe "Language Server Protocol (LSP) Engine" $ do Nothing -> expectationFailure "Expected executeCommand response" Just resp -> resp `shouldContain` "\"status\":\"sat\"" + it "ontologic.solve answers unknown when an axiom could not be sent to the solver" $ do + z3 <- findExecutable "z3" + cvc5 <- findExecutable "cvc5" + if isNothing z3 && isNothing cvc5 then pendingWith "z3/cvc5 not installed" else do + let docText = "(def-concept A)\\n(definedIn \\\"a\\\" \\\"b\\\")\\n" + openReq = "{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didOpen\",\"params\":{\"uri\":\"file:///partial.logic\",\"text\":\"" ++ docText ++ "\"}}" + (st, _, _) <- handleLSPRequestIO initialLSPState openReq + let cmdReq = "{\"jsonrpc\":\"2.0\",\"id\":132,\"method\":\"workspace/executeCommand\",\"params\":{\"command\":\"ontologic.solve\",\"uri\":\"file:///partial.logic\"}}" + (_, respOpt, _) <- handleLSPRequestIO st cmdReq + case respOpt of + Nothing -> expectationFailure "Expected executeCommand response" + Just resp -> do + resp `shouldContain` "\"status\":\"unknown\"" + resp `shouldContain` "could not be checked" + it "executes ontologic.solve via workspace/executeCommand with standard arguments array" $ do let docText = "(def-concept Widget)\\n(def-property weight Widget Float)\\n" openReq = "{\"jsonrpc\":\"2.0\",\"method\":\"textDocument/didOpen\",\"params\":{\"uri\":\"file:///args.logic\",\"text\":\"" ++ docText ++ "\"}}" diff --git a/test/LintSoundnessSpec.hs b/test/LintSoundnessSpec.hs new file mode 100644 index 0000000..577a33f --- /dev/null +++ b/test/LintSoundnessSpec.hs @@ -0,0 +1,124 @@ +module LintSoundnessSpec (spec) where + +import Test.Hspec +import Control.Monad (forM_, filterM) +import Data.List (isInfixOf, isSuffixOf, sort) +import System.Directory (listDirectory, doesDirectoryExist, doesFileExist) +import System.FilePath ((</>)) +import System.Timeout (timeout) +import qualified Data.Text as T +import Text.Megaparsec (parse) +import Control.Exception (evaluate) + +import OntoLogic +import Parser (parseRegistry) +import Linter +import Loader (loadRegistryWithImportsAndSource) +import IR.Clausify (clausifyTheory) +import IR.CNF (formatCNFTheory) + + + + +load :: String -> IO Registry +load src = case parse parseRegistry "<test>" (T.pack src) of + Left e -> fail (show e) + Right r -> return r + +errorsOf :: Registry -> [String] +errorsOf = map lintMessage . lintRegistryErrors + +spec :: Spec +spec = do + describe "linter never rejects a satisfiable theory (v1.8.4)" $ do + it "D1: two unary facts on different individuals are not a contradiction" $ do + r <- load "(def-concept Person)\n(def-concept Employee Person)\n(def-individual alice Person)\n(def-individual bob Person)\n(Employee alice)\n(not (Employee bob))\n" + lintRegistryFindings r `shouldBe` [] + it "D1: a ground fact plus an unrelated disjointness is fine" $ do + r <- load "(def-concept Person)\n(def-concept Employee Person)\n(def-concept Robot)\n(def-individual alice Person)\n(Employee alice)\n(forall (x) (implies (Robot x) (not (Person x))))\n" + lintRegistryFindings r `shouldBe` [] + it "D2: (implies ... false) is accepted" $ do + r <- load "(def-concept Cat)\n(def-concept Dog)\n(forall (x) (implies (and (Cat x) (Dog x)) false))\n" + lintRegistryFindings r `shouldBe` [] + it "D2: (not false) is accepted" $ do + r <- load "(def-concept A)\n(forall (x) (implies (A x) (not false)))\n" + lintRegistryFindings r `shouldBe` [] + it "D3: forall x exists y is not collapsed onto one witness" $ do + r <- load "(def-concept Node)\n(def-concept Red Node)\n(forall (x) (exists (y) (iff (Red x) (not (Red y)))))\n" + lintRegistryFindings r `shouldBe` [] + it "D4: bounds under different binder guards do not clash" $ do + r <- load "(def-concept Person)\n(def-concept Adult Person)\n(def-concept Child Person)\n(def-concept Member Person)\n(def-property fee Member Integer)\n(forall (x) (implies (Adult x) (not (Child x))))\n(forall ((x Adult)) (implies (Member x) (gte fee 100)))\n(forall ((x Child)) (implies (Member x) (lt fee 50)))\n" + lintRegistryFindings r `shouldBe` [] + it "a vacuous antecedent is not a contradiction" $ do + r <- load "(def-concept Oven)\n(def-concept Alarm)\n(def-property temp Oven Integer)\n(forall (o) (implies (and (Oven o) (gt temp 100) (lt temp 50)) (Alarm o)))\n" + lintRegistryFindings r `shouldBe` [] + + describe "real contradictions are still found" $ do + it "p and not p at the top of an axiom is an error" $ do + r <- load "(def-concept A)\n(and (A x) (not (A x)))\n" + errorsOf r `shouldSatisfy` any ("both exist" `isInfixOf`) + it "(not true) is an error" $ do + r <- load "(def-concept A)\n(not top)\n" + errorsOf r `shouldSatisfy` any ("bottom" `isInfixOf`) + it "contradictory bounds on one concept stay an error" $ do + r <- load "(def-concept Tank)\n(def-property cap Tank Integer)\n(forall (x) (implies (Tank x) (gt cap 10)))\n(forall (x) (implies (Tank x) (lt cap 5)))\n" + errorsOf r `shouldSatisfy` any ("contradiction" `isInfixOf`) + + describe "B4: propositional findings are warnings" $ do + it "a disjointness clash is a warning with exit-0 severity" $ do + r <- load "(def-concept A)\n(def-concept B A)\n(def-concept C A)\n(def-concept D B)\n(forall (x) (implies (B x) (not (A x))))\n" + let fs = lintRegistryFindings r + fs `shouldSatisfy` any (\f -> "Semantic contradiction" `isInfixOf` lintMessage f) + errorsOf r `shouldBe` [] + lintRegistryDiagnostics r `shouldSatisfy` any ("warning:" `isInfixOf`) + + describe "B5: undeclared references" $ do + it "an undeclared property type is an error" $ do + r <- load "(def-concept T)\n(def-property n T Int)\n" + errorsOf r `shouldSatisfy` any ("Undeclared property type: Int" `isInfixOf`) + it "DateTime is an error too" $ do + r <- load "(def-concept T)\n(def-property when T DateTime)\n" + errorsOf r `shouldSatisfy` any ("DateTime" `isInfixOf`) + it "a declared concept as property type is fine" $ do + r <- load "(def-concept T)\n(def-concept U)\n(def-property link T U)\n(def-property s T String)\n" + lintRegistryFindings r `shouldBe` [] + it "an undeclared predicate in an axiom is a warning, not an error" $ do + r <- load "(def-concept T)\n(forall (x) (implies (T x) (Ghost x)))\n" + errorsOf r `shouldBe` [] + map lintMessage (lintRegistryFindings r) `shouldSatisfy` any ("Ghost" `isInfixOf`) + it "an undeclared property in a bound is a warning" $ do + r <- load "(def-concept T)\n(forall (x) (implies (T x) (gt phantom 3)))\n" + errorsOf r `shouldBe` [] + map lintMessage (lintRegistryFindings r) `shouldSatisfy` any ("phantom" `isInfixOf`) + it "conflicting namespace prefixes survive loading and are an error" $ do + r <- load "(namespace a \"http://x/a#\")\n(namespace a \"http://x/b#\")\n(def-concept C)\n" + errorsOf (deduplicateRegistry r) `shouldSatisfy` any ("Duplicate namespace prefix" `isInfixOf`) + it "an exact repeated namespace is harmless" $ do + r <- load "(namespace a \"http://x/a#\")\n(namespace a \"http://x/a#\")\n(def-concept C)\n" + errorsOf (deduplicateRegistry r) `shouldBe` [] + + describe "D17: clausifier terminates on (not top)" $ do + it "clausifies (not top) as the empty clause" $ do + r <- load "(def-concept A)\n(not top)\n" + res <- timeout 5000000 (evaluate (length (formatCNFTheory (clausifyTheory r)))) + res `shouldSatisfy` (/= Nothing) + + describe "every shipped file lints clean" $ do + files <- runIO (concat <$> mapM logicFiles ["examples", "ontologic-lib"]) + forM_ (sort files) $ \f -> + it f $ do + res <- loadRegistryWithImportsAndSource f + case res of + Left e -> expectationFailure e + Right (reg, _) -> map lintMessage (lintRegistryFindings reg) `shouldBe` [] + +logicFiles :: FilePath -> IO [FilePath] +logicFiles dir = do + exists <- doesDirectoryExist dir + if not exists then return [] else do + names <- listDirectory dir + let paths = map (dir </>) names + dirs <- filterM doesDirectoryExist paths + plain <- filterM doesFileExist paths + sub <- concat <$> mapM logicFiles dirs + return ([ p | p <- plain, ".logic" `isSuffixOf` p ] ++ sub) diff --git a/test/MainSpec.hs b/test/MainSpec.hs index e882572..aeaeb47 100644 --- a/test/MainSpec.hs +++ b/test/MainSpec.hs @@ -5,6 +5,11 @@ import System.Process (readProcessWithExitCode) import System.Exit (ExitCode(..)) import System.Directory (removeDirectoryRecursive, doesFileExist, createDirectoryIfMissing, getTemporaryDirectory, getCurrentDirectory) import System.FilePath ((</>)) +import Data.Version (showVersion) +import Paths_ontologic (version) +import Data.List (isInfixOf, isPrefixOf) +import System.Directory (findExecutable) +import GHC.Clock (getMonotonicTime) spec :: Spec spec = do @@ -212,3 +217,64 @@ spec = do exitCode `shouldBe` ExitSuccess stdout `shouldContain` "Satisfiable (SAT)" stdout `shouldContain` "All concepts are satisfiable" + + describe "Partial checks are unknown, not consistent" $ do + let partial exe prover = it ("--solve -p " ++ prover ++ " answers unknown (exit 2) when axioms were not sent") $ do + found <- findExecutable exe + case found of + Nothing -> pendingWith (exe ++ " not installed") + Just _ -> do + (code, out, _) <- readProcessWithExitCode "stack" + ["exec", "ontologic-exe", "--", "-i", "test/fixtures/failclosed/free_var.logic", "-t", "solve", "-p", prover] "" + code `shouldBe` ExitFailure 2 + out `shouldNotContain` "Satisfiable (SAT)" + out `shouldContain` "could not be checked" + -- the message comes first, then the list of axioms that were not sent + let (ahead, rest) = breakOn "could not be checked" out + rest `shouldContain` "were not sent to the solver" + ahead `shouldNotContain` "were not sent to the solver" + partial "z3" "z3" + partial "cvc5" "cvc5" + + describe "Native prover honours the time limit" $ do + it "returns unknown within the limit plus grace on a theory it cannot saturate (two_color, -T 4)" $ do + t0 <- getMonotonicTime + -- Hard outer limit: if the in-process limit failed, the child is killed and the test fails. + (code, out, _) <- readProcessWithExitCode "timeout" + ["-s", "KILL", "40", "stack", "exec", "ontologic-exe", "--" + , "-i", "test/fixtures/failclosed/two_color.logic", "-t", "solve", "-p", "native", "-T", "4"] "" + t1 <- getMonotonicTime + code `shouldBe` ExitFailure 2 + out `shouldContain` "unknown" + (t1 - t0) `shouldSatisfy` (< 9) -- limit 4 s plus grace; one limit per phase would take 12 s + + describe "CLI surface (B7, B8)" $ do + it "--version prints the package version" $ do + (code, out, _) <- readProcessWithExitCode "stack" ["exec", "ontologic-exe", "--", "--version"] "" + code `shouldBe` ExitSuccess + out `shouldContain` ("ontologic " ++ showVersion version) + + it "--neo4j-edition rejects unknown values" $ do + (code, _, err) <- readProcessWithExitCode "stack" ["exec", "ontologic-exe", "--", "-i", "logic/fleet.logic", "-t", "neo4j", "-o", "/tmp/ontologic-neo-edition", "--neo4j-edition", "bogus"] "" + code `shouldNotBe` ExitSuccess + err `shouldContain` "unknown Neo4j edition" + + it "refuses absolute imports unless --allow-absolute-imports is given" $ do + tmp <- getTemporaryDirectory + let dir = tmp </> "ontologic-main-b7" + createDirectoryIfMissing True dir + writeFile (dir </> "ok.logic") "(def-concept Ok)\n" + writeFile (dir </> "root.logic") ("(import \"" ++ dir ++ "/ok.logic\")\n") + (c1, o1, _) <- readProcessWithExitCode "stack" ["exec", "ontologic-exe", "--", "-i", dir </> "root.logic"] "" + c1 `shouldNotBe` ExitSuccess + o1 `shouldSatisfy` ("Absolute import paths are not allowed" `isInfixOf`) + (c2, _, _) <- readProcessWithExitCode "stack" ["exec", "ontologic-exe", "--", "-i", dir </> "root.logic", "--allow-absolute-imports"] "" + c2 `shouldBe` ExitSuccess + +breakOn :: String -> String -> (String, String) +breakOn needle = go [] + where + go acc rest@(c:cs) + | needle `isPrefixOf` rest = (reverse acc, rest) + | otherwise = go (c : acc) cs + go acc [] = (reverse acc, []) diff --git a/test/REPLSpec.hs b/test/REPLSpec.hs index d83f325..0758fbb 100644 --- a/test/REPLSpec.hs +++ b/test/REPLSpec.hs @@ -7,6 +7,8 @@ import Solver (Prover(..)) import Control.Exception (bracket_) import System.Timeout (timeout) import Data.Maybe (isJust) +import System.Directory (findExecutable) +import Loader (loadRegistryWithImports) import System.Environment (lookupEnv, setEnv, unsetEnv) import Targets (optBaseIri) @@ -20,6 +22,10 @@ spec = describe "Interactive REPL Engine" $ do out `shouldContain` ":lint" out `shouldContain` ":ir" + it "reports an unknown :command instead of parsing it as DSL" $ do + (_, out) <- evalREPLCommand initialREPLState ":frobnicate" + out `shouldContain` "Unknown command: :frobnicate" + it "handles :show on empty state" $ do (_, out) <- evalREPLCommand initialREPLState ":show" out `shouldContain` "Active Registry State:" @@ -77,6 +83,24 @@ spec = describe "Interactive REPL Engine" $ do clearOut `shouldContain` "Session registry cleared." length (concepts (replRegistry clearedState)) `shouldBe` 0 + it ":solve answers unknown, then lists the axioms, when some were not sent" $ do + z3 <- findExecutable "z3" + case z3 of + Nothing -> pendingWith "z3 not installed" + Just _ -> do + r <- loadRegistryWithImports "test/fixtures/failclosed/smt_arity.logic" + reg <- either fail return r + let st = initialREPLState { replRegistry = reg, replProver = Z3 } + (_, out) <- evalREPLCommand st ":solve" + out `shouldContain` "could not be checked" + out `shouldContain` "were not sent to the solver" + out `shouldNotContain` "SMT Satisfiable (SAT)" + (_, mout) <- evalREPLCommand st ":model" + mout `shouldContain` "could not be checked" + -- A refuted subsumption over a partial theory is not a disproof. + (_, pout) <- evalREPLCommand st ":prove A B" + pout `shouldNotContain` "Theorem Disproved" + it "runs Z3 solver consistency check (:solve) from REPL" $ do (s1, _) <- evalREPLCommand initialREPLState "(def-concept Device)" (s2, _) <- evalREPLCommand s1 "(def-property battery Device Integer)" diff --git a/test/RegistrySpec.hs b/test/RegistrySpec.hs index ba7d1ff..e125f81 100644 --- a/test/RegistrySpec.hs +++ b/test/RegistrySpec.hs @@ -16,8 +16,8 @@ spec = describe "Registry helpers (#34)" $ do (a <> mempty) `shouldBe` a (mempty <> a) `shouldBe` a - it "deduplicates entries and keeps the last namespace per prefix (current Loader behavior)" $ do + it "deduplicates entries and collapses exact namespace repeats but keeps conflicting URIs for the linter" $ do let d = deduplicateRegistry (a <> b) concepts d `shouldBe` [("A", Nothing), ("B", Just "A")] - namespaces d `shouldBe` [NamespaceDecl "x" (Just "http://other/")] + namespaces d `shouldBe` [NamespaceDecl "x" (Just "http://x/"), NamespaceDecl "x" (Just "http://other/")] individuals d `shouldBe` [("i1", Nothing), ("i2", Just "A")] diff --git a/test/RegressionBugsSpec.hs b/test/RegressionBugsSpec.hs index 45c83ff..7f42202 100644 --- a/test/RegressionBugsSpec.hs +++ b/test/RegressionBugsSpec.hs @@ -141,13 +141,16 @@ spec = do describe "unsat-core explanation agrees with the consistency check" $ do it "cites the conflicting property bounds (Z3)" $ withProver "z3" $ do - checkConsistencyWith Z3 sensorReg >>= (`shouldSatisfy` isUnsat) - res <- explainUnsatWith Z3 sensorReg + -- The bounds hold for every SmartSensor, so they contradict only once one exists. + let reg = sensorReg { axioms = axioms sensorReg ++ [Exists "s" (Predicate "SmartSensor" [Var "s"])] } + checkConsistencyWith Z3 sensorReg >>= (`shouldSatisfy` isSat) + checkConsistencyWith Z3 reg >>= (`shouldSatisfy` isUnsat) + res <- explainUnsatWith Z3 reg case res of Left err -> expectationFailure err Right e -> do unsatCoreNames e `shouldSatisfy` (not . null) - unwords (unsatCoreDetails e) `shouldSatisfy` ("SmartSensor.batteryLevel" `isInfixOf`) + unwords (unsatCoreDetails e) `shouldSatisfy` ("batteryLevel" `isInfixOf`) describe "all-clear answers from provers without arithmetic" $ do it "recognises ordering comparisons, but not a relation that shares an operator name" $ do diff --git a/test/ShaclSpec.hs b/test/ShaclSpec.hs index c175223..f5100ea 100644 --- a/test/ShaclSpec.hs +++ b/test/ShaclSpec.hs @@ -129,5 +129,5 @@ spec = describe "SHACL Shapes Emitter" $ do ] } shacl = emitShacl reg - shacl `shouldContain` "sh:not [ sh:hasValue error ]" + shacl `shouldContain` "sh:not [ sh:hasValue \"error\" ]" shacl `shouldContain` "sh:hasValue 200" diff --git a/test/SolverSpec.hs b/test/SolverSpec.hs index 430d7ba..9ed3c2b 100644 --- a/test/SolverSpec.hs +++ b/test/SolverSpec.hs @@ -56,9 +56,11 @@ spec = describe "Multi-Prover SMT Solver & Automated Proof-Checking Engine" $ do let reg = emptyRegistry { concepts = [("Sensor", Nothing)] , properties = [Property "temp" "Sensor" PTInteger] - , axioms = [ForAll "s" (Implies (Predicate "Sensor" [Var "s"]) + , axioms = [ ForAll "s" (Implies (Predicate "Sensor" [Var "s"]) (And (Predicate "gt" [Var "temp", Constant "100"]) - (Predicate "lt" [Var "temp", Constant "50"])))] + (Predicate "lt" [Var "temp", Constant "50"]))) + -- An instance is asserted: without one the conflict only empties Sensor. + , Exists "s" (Predicate "Sensor" [Var "s"]) ] , relations = [] , namespaces = [] , imports = [] @@ -98,9 +100,10 @@ spec = describe "Multi-Prover SMT Solver & Automated Proof-Checking Engine" $ do let reg = emptyRegistry { concepts = [("Alarm", Nothing)] , properties = [Property "level" "Alarm" PTInteger] - , axioms = [ForAll "a" (Implies (Predicate "Alarm" [Var "a"]) + , axioms = [ ForAll "a" (Implies (Predicate "Alarm" [Var "a"]) (And (Predicate "gt" [Var "level", Constant "10"]) - (Predicate "lt" [Var "level", Constant "5"])))] + (Predicate "lt" [Var "level", Constant "5"]))) + , Exists "a" (Predicate "Alarm" [Var "a"]) ] , relations = [] , namespaces = [] , imports = [] @@ -470,8 +473,8 @@ spec = describe "Multi-Prover SMT Solver & Automated Proof-Checking Engine" $ do unlines (unsatCoreDetails expl) `shouldContain` "BrokenNode" describe "Solver Options & Resource Limits" $ do - it "provides defaultSolverOptions with no timeout or memory limits" $ do - optTimeoutSeconds defaultSolverOptions `shouldBe` Nothing + it "provides defaultSolverOptions with a 60 second timeout and no memory limit" $ do + optTimeoutSeconds defaultSolverOptions `shouldBe` Just 60 optMemoryLimitMb defaultSolverOptions `shouldBe` Nothing it "passes timeout and memory limits to Z3 without error" $ do diff --git a/test/fixtures/failclosed/04_function_terms.logic b/test/fixtures/failclosed/04_function_terms.logic new file mode 100644 index 0000000..a64baa0 --- /dev/null +++ b/test/fixtures/failclosed/04_function_terms.logic @@ -0,0 +1,13 @@ +; Copyright (c) 2026 OntoLogic Contributors +; SPDX-License-Identifier: Apache-2.0 + +(def-concept Node) +(def-individual root Node) +(def-individual leaf Node) + +(= (parent leaf) root) +(= (root_node) root) + +(forall (x) + (implies (Node x) + (= (identity (identity x)) x))) diff --git a/test/fixtures/failclosed/bounds_int_gap_universal.logic b/test/fixtures/failclosed/bounds_int_gap_universal.logic new file mode 100644 index 0000000..fe510e0 --- /dev/null +++ b/test/fixtures/failclosed/bounds_int_gap_universal.logic @@ -0,0 +1,7 @@ +; Ground truth: consistent (SAT). Tank is merely empty: no Integer is > 5 and < 6, and nothing asserts a Tank exists. +; Expected: consistency SAT, coherence reports Tank as empty. +(def-concept Tank) +(def-concept Valve) +(def-property level Tank Integer) +(forall (t) (implies (Tank t) (gt level 5))) +(forall (t) (implies (Tank t) (lt level 6))) diff --git a/test/fixtures/failclosed/eq_congruence.logic b/test/fixtures/failclosed/eq_congruence.logic new file mode 100644 index 0000000..fd270ad --- /dev/null +++ b/test/fixtures/failclosed/eq_congruence.logic @@ -0,0 +1,2 @@ +(def-concept A) +(exists (x y) (and (= x y) (P x) (not (P y)))) diff --git a/test/fixtures/failclosed/free_var.logic b/test/fixtures/failclosed/free_var.logic new file mode 100644 index 0000000..b31eb68 --- /dev/null +++ b/test/fixtures/failclosed/free_var.logic @@ -0,0 +1,6 @@ +; "plant1" is not declared. Ground truth with plant1 read as a constant: UNSAT. +(def-concept Plant) +(def-concept Place) +(def-relation located_in Plant Place) +(located_in plant1 berlin) +(forall (x y) (not (located_in x y))) diff --git a/test/fixtures/failclosed/guarded_int_gap.logic b/test/fixtures/failclosed/guarded_int_gap.logic new file mode 100644 index 0000000..736f0ec --- /dev/null +++ b/test/fixtures/failclosed/guarded_int_gap.logic @@ -0,0 +1,10 @@ +; Ground truth: SAT and coherent (adult member fee 10, child member fee 2). +(def-concept Person) +(def-concept Adult Person) +(def-concept Child Person) +(def-concept Member Person) +(def-property fee Member Integer) +(forall ((x Adult)) (implies (Member x) (gt fee 5))) +(forall ((x Child)) (implies (Member x) (lt fee 6))) +(exists (x) (and (Member x) (Adult x) (eq fee 10))) +(exists (x) (and (Member x) (Child x) (eq fee 2))) diff --git a/test/fixtures/failclosed/ind_unary_fact_vampire.logic b/test/fixtures/failclosed/ind_unary_fact_vampire.logic new file mode 100644 index 0000000..1eb6709 --- /dev/null +++ b/test/fixtures/failclosed/ind_unary_fact_vampire.logic @@ -0,0 +1,9 @@ +; Ground truth: UNSAT. alice is an Employee; every Employee has a badge; nothing has a badge. +(def-concept Person) +(def-concept Employee Person) +(def-concept Badge) +(def-relation has_badge Employee Badge) +(def-individual alice Person) +(Employee alice) +(forall (x) (implies (Employee x) (exists (y) (has_badge x y)))) +(forall (x y) (not (has_badge x y))) diff --git a/test/fixtures/failclosed/odd_ident.logic b/test/fixtures/failclosed/odd_ident.logic new file mode 100644 index 0000000..159c01d --- /dev/null +++ b/test/fixtures/failclosed/odd_ident.logic @@ -0,0 +1,6 @@ +; Ground truth: UNSAT. Identifiers use characters the language reference allows (/ + '). +(def-concept Read/Write) +(def-concept C++Module) +(def-relation uses C++Module Read/Write) +(exists (x y) (uses x y)) +(forall (x y) (not (uses x y))) diff --git a/test/fixtures/failclosed/smt_arity.logic b/test/fixtures/failclosed/smt_arity.logic new file mode 100644 index 0000000..6e89dbd --- /dev/null +++ b/test/fixtures/failclosed/smt_arity.logic @@ -0,0 +1,7 @@ +; Ground truth: UNSAT. A ternary relation is declared but used with two arguments. +(def-concept A) +(def-concept B) +(def-concept C) +(def-relation between A B C) +(exists (x y) (between x y)) +(forall (x y) (not (between x y))) diff --git a/test/fixtures/failclosed/smt_const_arg.logic b/test/fixtures/failclosed/smt_const_arg.logic new file mode 100644 index 0000000..8628cf5 --- /dev/null +++ b/test/fixtures/failclosed/smt_const_arg.logic @@ -0,0 +1,4 @@ +; Ground truth: UNSAT. 7 is Prime; nothing is Prime. +(def-concept Prime) +(Prime 7) +(forall (x) (not (Prime x))) diff --git a/test/fixtures/failclosed/smt_string_arg.logic b/test/fixtures/failclosed/smt_string_arg.logic new file mode 100644 index 0000000..e3b5b56 --- /dev/null +++ b/test/fixtures/failclosed/smt_string_arg.logic @@ -0,0 +1,7 @@ +; Ground truth: UNSAT. plant1 is located in "Berlin"; nothing is located anywhere. +(def-concept Plant) +(def-concept Place) +(def-relation located_in Plant Place) +(def-individual plant1 Plant) +(located_in plant1 "Berlin") +(forall (x y) (not (located_in x y))) diff --git a/test/fixtures/failclosed/string_space_tptp.logic b/test/fixtures/failclosed/string_space_tptp.logic new file mode 100644 index 0000000..651c983 --- /dev/null +++ b/test/fixtures/failclosed/string_space_tptp.logic @@ -0,0 +1,8 @@ +; Ground truth: UNSAT. Every Task has an owner; no Task has an owner. A string with a space is also used. +(def-concept Task) +(def-concept Person) +(def-relation owner Task Person) +(def-property status Task String) +(exists (t) (and (Task t) (eq status "in progress"))) +(forall (t) (implies (Task t) (exists (p) (owner t p)))) +(forall (t p) (not (owner t p))) diff --git a/test/fixtures/failclosed/subs_eq.logic b/test/fixtures/failclosed/subs_eq.logic new file mode 100644 index 0000000..3ce05e1 --- /dev/null +++ b/test/fixtures/failclosed/subs_eq.logic @@ -0,0 +1,5 @@ +; Ground truth: A ⊑ B. Every A equals its own image under f, and every image under f is a B. +(def-concept A) +(def-concept B) +(forall (x) (implies (A x) (= (f x) x))) +(forall (x) (B (f x))) diff --git a/test/fixtures/failclosed/subs_ind.logic b/test/fixtures/failclosed/subs_ind.logic new file mode 100644 index 0000000..6e09539 --- /dev/null +++ b/test/fixtures/failclosed/subs_ind.logic @@ -0,0 +1,7 @@ +; Ground truth: A ⊑ B (declared axiom); B ⋢ A. One ground fact about an individual is present. +(def-concept A) +(def-concept B) +(def-concept C) +(def-individual c1 C) +(C c1) +(forall (x) (implies (A x) (B x))) diff --git a/test/fixtures/failclosed/two_color.logic b/test/fixtures/failclosed/two_color.logic new file mode 100644 index 0000000..f5c38f8 --- /dev/null +++ b/test/fixtures/failclosed/two_color.logic @@ -0,0 +1,3 @@ +(def-concept Node) +(def-concept Red Node) +(forall (x) (exists (y) (iff (Red x) (not (Red y)))))