diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 5944926..031e9cb 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -4,14 +4,15 @@ Copyright (c) Jonathan D.A. Jewell --> ## Machine-Readable Artefacts -The following files in `.machine_readable/` contain structured project metadata: - -- `STATE.scm` - Current project state and progress -- `META.scm` - Architecture decisions and development practices -- `ECOSYSTEM.scm` - Position in the ecosystem and related projects -- `AGENTIC.scm` - AI agent interaction patterns -- `NEUROSYM.scm` - Neurosymbolic integration config -- `PLAYBOOK.scm` - Operational runbook +The 6 core A2ML metadata files live in `.machine_readable/6a2/` (the canonical +RSR layout — see https://github.com/hyperpolymath/standards): + +- `STATE.a2ml` - Current project state and progress +- `META.a2ml` - Architecture decisions and development practices +- `ECOSYSTEM.a2ml` - Position in the ecosystem and related projects +- `AGENTIC.a2ml` - AI agent interaction patterns +- `NEUROSYM.a2ml` - Neurosymbolic integration config +- `PLAYBOOK.a2ml` - Operational runbook --- diff --git a/.machine_readable/6a2/AGENTIC.a2ml b/.machine_readable/6a2/AGENTIC.a2ml index cd1fb1d..260695e 100644 --- a/.machine_readable/6a2/AGENTIC.a2ml +++ b/.machine_readable/6a2/AGENTIC.a2ml @@ -4,7 +4,7 @@ # AGENTIC.a2ml — AI agent constraints and capabilities [metadata] version = "0.1.0" -last-updated = "2026-04-11" +last-updated = "2026-06-18" [agent-permissions] can-edit-source = true @@ -28,6 +28,12 @@ allow-silent-skip = false require-rerun-after-fix = true release-claim-requires-hard-pass = true +[reflexion] +# The reflexion design layer is advisory: it emits design obligations that gate +# changes to the language, but never auto-mutates the AST, compiler, or runtime. +obligations-are-advisory = true +never-auto-mutate-semantics = true + [automation-hooks] # on-enter: Read 0-AI-MANIFEST.a2ml, then STATE.a2ml # on-exit: Update STATE.a2ml with session outcomes diff --git a/.machine_readable/6a2/ECOSYSTEM.a2ml b/.machine_readable/6a2/ECOSYSTEM.a2ml index 0a69bf9..f38d1e8 100644 --- a/.machine_readable/6a2/ECOSYSTEM.a2ml +++ b/.machine_readable/6a2/ECOSYSTEM.a2ml @@ -4,17 +4,25 @@ # ECOSYSTEM.a2ml — Phronesis ecosystem position [metadata] version = "1.0" -last-updated = "2026-04-11" +last-updated = "2026-06-18" [project] name = "Phronesis" -purpose = "" -role = "" +purpose = "Neuro-symbolic policy language for provably-safe agentic ethical reasoning on the BEAM." +role = "language-and-runtime" [position-in-ecosystem] -category = "" +category = "nextgen-language" [related-projects] projects = [ - # No related projects recorded + { name = "phronesiser", relation = "sibling", note = "The -iser that adds provably-safe ethical constraints to AI agents via Phronesis deontic logic." }, + { name = "standards", relation = "depends-on", note = "Estate standards: RSR template, A2ML format family, licence policy." }, + { name = "rsr-template-repo", relation = "templated-from", note = "Rhodium Standard Repository template (.machine_readable/6a2 layout, contractiles)." }, + { name = "hypatia", relation = "ci", note = "Neurosymbolic CI scanning (report-format = logtalk)." }, + { name = "gitbot-fleet", relation = "ci", note = "Learning / feedback submission." }, + { name = "a2ml-validate-action", relation = "ci", note = "Validates the .machine_readable A2ML artefacts." }, ] + +[boundaries] +note = "A reflexion design-self-relation layer (claims / judgement-evidence graph / invariant-path equivalence / revaluation) was added 2026-06; it observes the toolchain and gates design changes but never auto-mutates semantics." diff --git a/.machine_readable/6a2/META.a2ml b/.machine_readable/6a2/META.a2ml index 0067359..b2a916b 100644 --- a/.machine_readable/6a2/META.a2ml +++ b/.machine_readable/6a2/META.a2ml @@ -4,7 +4,7 @@ # META.a2ml — Phronesis meta-level information [metadata] version = "0.1.0" -last-updated = "2026-04-11" +last-updated = "2026-06-18" [project-info] license = "MPL-2.0" @@ -12,7 +12,10 @@ author = "Jonathan D.A. Jewell (hyperpolymath)" [architecture-decisions] decisions = [ - # No ADRs recorded + { id = "ADR-0001", title = "BEAM/Elixir reference runtime with a Rust to WASM production compiler", status = "accepted" }, + { id = "ADR-0002", title = "Idris2 ABI + Zig FFI as the cross-language boundary standard", status = "accepted" }, + { id = "ADR-0003", title = "Reflexion layer: design self-relation that gates changes, never auto-mutates semantics", status = "proposed" }, + { id = "ADR-0004", title = "Dual licence: MPL-2.0 for code, CC-BY-SA-4.0 for documentation/content", status = "accepted" }, ] [development-practices] diff --git a/.machine_readable/6a2/NEUROSYM.a2ml b/.machine_readable/6a2/NEUROSYM.a2ml index e1d34c0..b9e6876 100644 --- a/.machine_readable/6a2/NEUROSYM.a2ml +++ b/.machine_readable/6a2/NEUROSYM.a2ml @@ -4,7 +4,7 @@ # NEUROSYM.a2ml — Neurosymbolic integration metadata [metadata] version = "0.1.0" -last-updated = "2026-04-11" +last-updated = "2026-06-18" [hypatia-config] scan-enabled = true diff --git a/.machine_readable/6a2/PLAYBOOK.a2ml b/.machine_readable/6a2/PLAYBOOK.a2ml index 5003fd0..1bc3418 100644 --- a/.machine_readable/6a2/PLAYBOOK.a2ml +++ b/.machine_readable/6a2/PLAYBOOK.a2ml @@ -4,7 +4,7 @@ # PLAYBOOK.a2ml — Operational playbook [metadata] version = "0.1.0" -last-updated = "2026-04-11" +last-updated = "2026-06-18" [deployment] # method = "gitops" # gitops | manual | ci-triggered diff --git a/.machine_readable/6a2/README.adoc b/.machine_readable/6a2/README.adoc index ac38c25..c851cfb 100644 --- a/.machine_readable/6a2/README.adoc +++ b/.machine_readable/6a2/README.adoc @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: MPL-2.0 +// SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell # A2ML 6a2 Directory diff --git a/.machine_readable/6a2/STATE.a2ml b/.machine_readable/6a2/STATE.a2ml index ddb7392..cbf251b 100644 --- a/.machine_readable/6a2/STATE.a2ml +++ b/.machine_readable/6a2/STATE.a2ml @@ -5,56 +5,45 @@ [metadata] project = "phronesis" version = "0.9.0" -last-updated = "2026-03-14" +last-updated = "2026-06-18" status = "active" -session = "converted from scheme — 2026-04-11" +session = "reflexion design layer + docs/metadata/licence sync — 2026-06-18" [project-context] name = "Phronesis" -purpose = """Scale testing, edge case handling, production deployment""" -completion-percentage = 95 +purpose = """Neuro-symbolic policy language for provably-safe agentic ethical reasoning on the BEAM.""" +completion-percentage = 80 [position] -phase = "production-ready" # design | implementation | testing | maintenance | archived +phase = "implementation" # design | implementation | testing | maintenance | archived maturity = "experimental" # experimental | alpha | beta | production | lts [route-to-mvp] milestones = [ - # No milestones recorded + { name = "Lexer / parser / AST", completion = 100 }, + { name = "Type checker + analyzer", completion = 100 }, + { name = "Interpreter + tracing + decision traces", completion = 100 }, + { name = "LSP / debugger / profiler / doc-generator", completion = 100 }, + { name = "Consensus (Raft via :ra) runtime + TLA+ spec", completion = 80 }, + { name = "Reflexion design layer (claims / JEG / invariant-path / revaluation)", completion = 70 }, + { name = "Rust to WASM production compiler", completion = 20 }, + { name = "Idris2 ABI + Zig FFI boundary", completion = 30 }, ] [blockers-and-issues] issues = [ - # No blockers recorded + { id = "pre-existing-test-failures", note = "DebuggerTest (Trace.merge/2 undefined; State.variables), DocGeneratorTest, IncrementalLexerTest, ConformanceTest 04_boolean_logic — predate the reflexion work" }, + { id = "compiler-backend", note = "Rust to WASM codegen is still AST scaffolding only" }, ] [critical-next-actions] actions = [ - "Write comprehensive tests for lexer, parser, interpreter, consensus, RPKI", - "8-12 hours", - "Scale test and real-world BGP feed testing", - "15-20 hours", - "Add Idris2 ABI definitions and Zig FFI layer", - "15-20 hours", - ") - (achieved ", - ") - (evidence - (unit ", - ") - (smoke ", - ") - (p2p ", - ") - (e2e ", - ") - (aspect ", - ") - (contract ", - ") - (benchmarks ", + "Repair pre-existing test failures (Trace.merge/2 in debugger; State.variables field)", + "Wire reflexion claim ingest for the compiler, formal/proof, and benchmark sources", + "Advance the Rust to WASM production compiler beyond AST scaffolding", + "Add Idris2 ABI definitions and the Zig FFI layer", ] [maintenance-status] -last-run-utc = "2026-03-14T00:00:00Z" -last-result = "unknown" # unknown | pass | warn | fail +last-run-utc = "2026-06-18T00:00:00Z" +last-result = "warn" # unknown | pass | warn | fail (reflexion suite green; pre-existing failures remain) diff --git a/.machine_readable/contractiles/Trustfile.a2ml b/.machine_readable/contractiles/Trustfile.a2ml index e2028b5..244ed0f 100644 --- a/.machine_readable/contractiles/Trustfile.a2ml +++ b/.machine_readable/contractiles/Trustfile.a2ml @@ -54,7 +54,7 @@ Current trust level: maximal #### license-content - description: LICENSE contains expected identifier -- run: grep -q 'PMPL\|MPL\|MIT\|Apache\|LGPL' LICENSE +- run: grep -q 'MPL\|MIT\|Apache\|LGPL\|CC-BY-SA' LICENSE - severity: warning ## Template-Specific Trust diff --git a/0-AI-MANIFEST.a2ml b/0-AI-MANIFEST.a2ml index 4e48465..9c6a798 100644 --- a/0-AI-MANIFEST.a2ml +++ b/0-AI-MANIFEST.a2ml @@ -11,15 +11,15 @@ This is the AI manifest for **phronesis**. It declares: ## CANONICAL LOCATIONS (UNIVERSAL RULE) -### Machine-Readable Metadata: `.machine_readable/` ONLY +### Machine-Readable Metadata: `.machine_readable/6a2/` ONLY -These 6 SCM files MUST exist in `.machine_readable/` directory ONLY: -1. **STATE.scm** - Project state, progress, blockers -2. **META.scm** - Architecture decisions, governance -3. **ECOSYSTEM.scm** - Position in ecosystem, relationships -4. **AGENTIC.scm** - AI agent interaction patterns -5. **NEUROSYM.scm** - Neurosymbolic integration config -6. **PLAYBOOK.scm** - Operational runbook +These 6 A2ML files MUST exist in the `.machine_readable/6a2/` directory ONLY: +1. **STATE.a2ml** - Project state, progress, blockers +2. **META.a2ml** - Architecture decisions, governance +3. **ECOSYSTEM.a2ml** - Position in ecosystem, relationships +4. **AGENTIC.a2ml** - AI agent interaction patterns +5. **NEUROSYM.a2ml** - Neurosymbolic integration config +6. **PLAYBOOK.a2ml** - Operational runbook **CRITICAL:** If ANY of these files exist in the root directory, this is an ERROR. @@ -40,9 +40,9 @@ Bot-specific instructions for: ## CORE INVARIANTS -1. **No SCM duplication** - Root must NOT contain STATE.scm, META.scm, etc. -2. **Single source of truth** - `.machine_readable/` is authoritative -3. **No stale metadata** - If root SCMs exist, they are OUT OF DATE +1. **No metadata duplication** - Root must NOT contain STATE.a2ml, META.a2ml, etc. +2. **Single source of truth** - `.machine_readable/6a2/` is authoritative +3. **No stale metadata** - If root metadata files exist, they are OUT OF DATE 4. **License consistency** - All code MPL-2.0 unless platform requires MPL-2.0 5. **Author attribution** - Always "Jonathan D.A. Jewell " @@ -55,16 +55,21 @@ This repo contains: ``` phronesis/ ├── 0-AI-MANIFEST.a2ml # THIS FILE (start here) -├── README.md # Project overview -├── [your source files] # Main code -├── .machine_readable/ # SCM files (6 files) -│ ├── STATE.scm -│ ├── META.scm -│ ├── ECOSYSTEM.scm -│ ├── AGENTIC.scm -│ ├── NEUROSYM.scm -│ └── PLAYBOOK.scm -└── .bot_directives/ # Bot instructions +├── README.adoc # Project overview +├── lib/phronesis/ # Reference implementation (Elixir/BEAM) +├── compiler/ # Rust → WASM compiler +├── spec/ formal/ academic/ # Grammar, semantics, proofs +├── docs/ # AsciiDoc design docs (incl. REFLEXION.adoc) +├── .machine_readable/ +│ ├── 6a2/ # The 6 core A2ML files +│ │ ├── STATE.a2ml +│ │ ├── META.a2ml +│ │ ├── ECOSYSTEM.a2ml +│ │ ├── AGENTIC.a2ml +│ │ ├── NEUROSYM.a2ml +│ │ └── PLAYBOOK.a2ml +│ └── contractiles/ # Mustfile / Trustfile / Justfile / etc. +└── .github/workflows/ # CI/CD ``` ## SESSION STARTUP CHECKLIST @@ -73,8 +78,8 @@ phronesis/ ✅ Understand canonical locations (.machine_readable/, .bot_directives/) ✅ Know the invariants (no SCM duplication, etc.) ✅ Check for MCP enforcement (if applicable) -✅ Read `.machine_readable/STATE.scm` for current status -✅ Read `.machine_readable/AGENTIC.scm` for interaction patterns +✅ Read `.machine_readable/6a2/STATE.a2ml` for current status +✅ Read `.machine_readable/6a2/AGENTIC.a2ml` for interaction patterns ## LIFECYCLE HOOKS @@ -86,7 +91,7 @@ When starting a new session: 2. Log session start (optional but recommended) - Format: `[YYYY-MM-DD HH:MM:SS] Session started: [agent-name]` - Location: `.machine_readable/session-log.txt` -3. Read `.machine_readable/STATE.scm` +3. Read `.machine_readable/6a2/STATE.a2ml` 4. Check for blockers 5. State understanding of canonical locations @@ -94,7 +99,7 @@ When starting a new session: When ending a session: -1. Update `.machine_readable/STATE.scm` if changes made +1. Update `.machine_readable/6a2/STATE.a2ml` if changes made 2. Log session end (optional but recommended) - Format: `[YYYY-MM-DD HH:MM:SS] Session ended: [summary]` - Location: `.machine_readable/session-log.txt` @@ -105,13 +110,13 @@ When ending a session: After reading this file, demonstrate understanding by stating: -**"I have read the AI manifest. SCM files are located in `.machine_readable/` ONLY, bot directives in `.bot_directives/`, and I will not create duplicate files in the root directory."** +**"I have read the AI manifest. The 6 core A2ML files are located in `.machine_readable/6a2/` ONLY, and I will not create duplicate metadata files in the root directory."** ## META - **Format Version:** 1.0.0 -- **Created:** [DATE] -- **Maintained By:** [YOUR-NAME/ORG] +- **Created:** 2026 +- **Maintained By:** Jonathan D.A. Jewell (hyperpolymath) - **License:** MPL-2.0 - **Protocol:** https://github.com/hyperpolymath/0-ai-gatekeeper-protocol diff --git a/CONTRIBUTING.adoc b/CONTRIBUTING.adoc deleted file mode 100644 index 2ead10c..0000000 --- a/CONTRIBUTING.adoc +++ /dev/null @@ -1,21 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) Jonathan D.A. Jewell -= Contributing Guide - -== Getting Started - -1. Fork the repository -2. Create a feature branch from `main` -3. Sign off commits (`git commit -s`) -4. Submit a pull request - -== Commit Guidelines - -* Conventional commits: `type(scope): description` -* Sign all commits (DCO required) -* Atomic, focused commits - -== License - -Contributions licensed under project license. - diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ac18434..5696af9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,51 +2,50 @@ SPDX-License-Identifier: MPL-2.0 Copyright (c) Jonathan D.A. Jewell --> +# Contributing to Phronesis + +Thanks for your interest in contributing! Phronesis is a neuro-symbolic policy +language for provably-safe agentic ethical reasoning, with an Elixir/BEAM +reference implementation and a Rust → WASM production compiler. + +## Getting Started + +```bash # Clone the repository git clone https://github.com/hyperpolymath/phronesis.git cd phronesis -# Using Nix (recommended for reproducibility) -nix develop - -# Or using toolbox/distrobox -toolbox create phronesis-dev -toolbox enter phronesis-dev -# Install dependencies manually +# Install dependencies (BEAM toolchain + just) +mix deps.get # Verify setup -just check # or: cargo check / mix compile / etc. -just test # Run test suite +just build # mix compile +just test # run the test suite ``` ### Repository Structure ``` phronesis/ -├── src/ # Source code (Perimeter 1-2) -├── lib/ # Library code (Perimeter 1-2) -├── extensions/ # Extensions (Perimeter 2) -├── plugins/ # Plugins (Perimeter 2) -├── tools/ # Tooling (Perimeter 2) -├── docs/ # Documentation (Perimeter 3) -│ ├── architecture/ # ADRs, specs (Perimeter 2) -│ └── proposals/ # RFCs (Perimeter 3) -├── examples/ # Examples (Perimeter 3) -├── spec/ # Spec tests (Perimeter 3) -├── tests/ # Test suite (Perimeter 2-3) -├── .well-known/ # Protocol files (Perimeter 1-3) -├── .github/ # GitHub config (Perimeter 1) -│ ├── ISSUE_TEMPLATE/ -│ └── workflows/ -├── CHANGELOG.md -├── CODE_OF_CONDUCT.md -├── CONTRIBUTING.md # This file -├── GOVERNANCE.md -├── LICENSE -├── MAINTAINERS.md -├── README.adoc -├── SECURITY.md -├── flake.nix # Nix flake (Perimeter 1) -└── Justfile # Task runner (Perimeter 1) +├── lib/phronesis/ # Reference implementation (Elixir/BEAM): +│ # lexer, parser, type checker, interpreter, +│ # consensus, LSP, debugger, profiler, reflexion +├── compiler/ # Rust → WASM compiler (phronesis-ast, phronesis-wasm) +├── spec/ # Grammar (EBNF) + formal semantics +├── formal/ # TLA+ consensus specification +├── academic/ # Formal proofs (Lean4 / Agda / Coq) +├── conformance/ # Conformance test suites +├── bench/ # Benchmarks +├── docs/ # AsciiDoc design docs (incl. REFLEXION.adoc) +├── examples/ # Example .phr policies +├── test/ # ExUnit test suite +├── editors/ # VSCode extension + grammars +├── .machine_readable/ # A2ML metadata (6a2/) + contractiles +├── .github/workflows/ # CI/CD +├── CHANGELOG.md CODE_OF_CONDUCT.md CONTRIBUTING.md SECURITY.md +├── GOVERNANCE.adoc MAINTAINERS.adoc README.adoc EXPLAINME.adoc +├── LICENSE LICENSES/ # MPL-2.0 (code) + CC-BY-SA-4.0 (docs) +├── mix.exs Justfile Mustfile +└── guix.scm ``` --- diff --git a/EXPLAINME.adoc b/EXPLAINME.adoc index 3e4192d..0fed259 100644 --- a/EXPLAINME.adoc +++ b/EXPLAINME.adoc @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: MPL-2.0 +// SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Phronesis — Show Me The Receipts :toc: diff --git a/GOVERNANCE.adoc b/GOVERNANCE.adoc index 8bbf167..e41020d 100644 --- a/GOVERNANCE.adoc +++ b/GOVERNANCE.adoc @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: MPL-2.0 +// SPDX-License-Identifier: CC-BY-SA-4.0 // SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell = Governance Model :toc: preamble diff --git a/Justfile b/Justfile index f627ef5..c3263cb 100644 --- a/Justfile +++ b/Justfile @@ -1,5 +1,5 @@ import? "contractile.just" -// Owner: Jonathan D.A. Jewell +# Owner: Jonathan D.A. Jewell # SPDX-License-Identifier: MPL-2.0 # SPDX-FileCopyrightText: 2025 Phronesis Contributors @@ -20,6 +20,14 @@ test: demo: mix run -e 'Phronesis.Demo.run()' +# Run the reflexion design-review pipeline tests +reflexion-test: + mix test test/reflexion test/reflexion_test.exs + +# Demo the reflexion pipeline on two policy versions (drops a REPORT mandate) +reflexion-demo: + mix run --no-start -e 'Phronesis.Reflexion.demo()' + # Run conformance test suite conformance: mix run -e 'Phronesis.Demo.run_conformance()' diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index ec540b3..0000000 --- a/LICENSE.txt +++ /dev/null @@ -1,153 +0,0 @@ -SPDX-License-Identifier: MPL-2.0 -SPDX-FileCopyrightText: 2024-2025 Palimpsest Stewardship Council - -================================================================================ -PALIMPSEST-MPL LICENSE VERSION 1.0 -================================================================================ - -File-level copyleft with ethical use and quantum-safe provenance - -Based on Mozilla Public License 2.0 - --------------------------------------------------------------------------------- -PREAMBLE --------------------------------------------------------------------------------- - -This License extends the Mozilla Public License 2.0 (MPL-2.0) with provisions -for ethical use, post-quantum cryptographic provenance, and emotional lineage -protection. The base MPL-2.0 terms apply except where explicitly modified by -the Exhibits below. - -Like a palimpsest manuscript where each layer builds upon what came before, -this license recognizes that creative works carry history, context, and meaning -that transcend mere code or text. - --------------------------------------------------------------------------------- -SECTION 1: BASE LICENSE --------------------------------------------------------------------------------- - -This License incorporates the full text of Mozilla Public License 2.0 by -reference. The complete MPL-2.0 text is available at: -https://www.mozilla.org/en-US/MPL/2.0/ - -All terms, conditions, and definitions from MPL-2.0 apply except where -explicitly modified by the Exhibits in this License. - --------------------------------------------------------------------------------- -SECTION 2: ADDITIONAL DEFINITIONS --------------------------------------------------------------------------------- - -2.1. "Emotional Lineage" - means the narrative, cultural, symbolic, and contextual meaning embedded - in Covered Software, including but not limited to: protest traditions, - cultural heritage, trauma narratives, and community stories. - -2.2. "Provenance Metadata" - means cryptographically signed attribution information attached to or - associated with Covered Software, including author identities, timestamps, - modification history, and lineage references. - -2.3. "Non-Interpretive System" - means any automated system that processes Covered Software without - preserving or considering its Emotional Lineage, including but not - limited to: AI training pipelines, content aggregators, and automated - summarization tools. - -2.4. "Quantum-Safe Signature" - means a cryptographic signature using algorithms resistant to attacks - by quantum computers, as specified in Exhibit B. - --------------------------------------------------------------------------------- -SECTION 3: ETHICAL USE REQUIREMENTS --------------------------------------------------------------------------------- - -In addition to the rights and obligations under MPL-2.0: - -3.1. Emotional Lineage Preservation - You must make reasonable efforts to preserve and communicate the - Emotional Lineage of Covered Software when distributing or creating - derivative works. This includes maintaining narrative context, cultural - attributions, and symbolic meaning where documented. - -3.2. Non-Interpretive System Notice - If You use Covered Software as input to a Non-Interpretive System, You - must: - (a) document such use in a publicly accessible manner; and - (b) not claim that outputs of such systems carry the Emotional Lineage - of the original work without explicit permission from Contributors. - -3.3. Ethical Use Declaration - Commercial use of Covered Software requires acknowledgment that You have - read and understood Exhibit A (Ethical Use Guidelines) and agree to act - in good faith accordance with its principles. - -See Exhibit A for complete Ethical Use Guidelines. - --------------------------------------------------------------------------------- -SECTION 4: PROVENANCE REQUIREMENTS --------------------------------------------------------------------------------- - -4.1. Metadata Preservation - You must not strip, alter, or obscure Provenance Metadata from Covered - Software except where technically necessary and with clear documentation - of any changes. - -4.2. Quantum-Safe Provenance (Optional) - Contributors may sign their Contributions using Quantum-Safe Signatures. - If Quantum-Safe Signatures are present, You must preserve them in all - distributions. - -4.3. Lineage Chain - When creating derivative works, You should extend the provenance chain - to include Your own contributions, maintaining cryptographic linkage to - prior Contributors where feasible. - -See Exhibit B for Quantum-Safe Provenance specifications. - --------------------------------------------------------------------------------- -SECTION 5: GOVERNANCE --------------------------------------------------------------------------------- - -5.1. Stewardship Council - This License is maintained by the Palimpsest Stewardship Council, which - may issue clarifications, interpretive guidance, and future versions. - -5.2. Version Selection - You may use Covered Software under this version of the License or any - later version published by the Palimpsest Stewardship Council. - -5.3. Dispute Resolution - Disputes regarding interpretation of Ethical Use Requirements (Section 3) - should first be submitted to the Palimpsest Stewardship Council for - non-binding guidance before pursuing legal remedies. - --------------------------------------------------------------------------------- -SECTION 6: COMPATIBILITY --------------------------------------------------------------------------------- - -6.1. MPL-2.0 Compatibility - Covered Software under this License may be combined with software under - MPL-2.0. The combined work must comply with both licenses. - -6.2. Secondary Licenses - The Secondary License provisions of MPL-2.0 Section 3.3 apply to this - License. - --------------------------------------------------------------------------------- -EXHIBITS --------------------------------------------------------------------------------- - -Exhibit A - Ethical Use Guidelines -Exhibit B - Quantum-Safe Provenance Specification - -See separate files: -- EXHIBIT-A-ETHICAL-USE.txt -- EXHIBIT-B-QUANTUM-SAFE.txt - --------------------------------------------------------------------------------- -END OF PALIMPSEST-MPL LICENSE VERSION 1.0 --------------------------------------------------------------------------------- - -For questions about this License: -- Repository: https://github.com/hyperpolymath/palimpsest-license -- Council: contact via repository Issues diff --git a/LICENSES/CC-BY-SA-4.0.txt b/LICENSES/CC-BY-SA-4.0.txt new file mode 100644 index 0000000..835a683 --- /dev/null +++ b/LICENSES/CC-BY-SA-4.0.txt @@ -0,0 +1,170 @@ +Creative Commons Attribution-ShareAlike 4.0 International + + Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. + +Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. + +Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. + +Creative Commons Attribution-ShareAlike 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. + + a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + + e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + + i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. + + k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + + 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. Downstream recipients. + + A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. + + C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. + + 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; + + b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + + a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. + + b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. + + c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + + a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + + d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +Section 8 – Interpretation. + + a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + + c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + + d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/LICENSES/MPL-2.0.txt b/LICENSES/MPL-2.0.txt new file mode 100644 index 0000000..14e2f77 --- /dev/null +++ b/LICENSES/MPL-2.0.txt @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/LSP-IMPLEMENTATION-SUMMARY.md b/LSP-IMPLEMENTATION-SUMMARY.md index 6769e0c..0188a77 100644 --- a/LSP-IMPLEMENTATION-SUMMARY.md +++ b/LSP-IMPLEMENTATION-SUMMARY.md @@ -235,15 +235,17 @@ Per LSP spec, the server advertises: - **Hover latency:** <5ms - **Diagnostics:** Real-time on document change -## Next Steps (Not Implemented) +## Status of Follow-on Tooling -Based on TOOLCHAIN-WISHLIST.md, the next sequential items are: +The items that were "next" at the time of the LSP work have since landed: -1. **Debugger** (1-2 weeks) - Set breakpoints, inspect state, step execution -2. **Profiler** (1 week) - Performance analysis -3. **Documentation Generator** (1 week) - Extract docs from policies -4. **REPL Enhancements** (1 week) - Auto-completion, history, multi-line -5. **Package Manager** (2-3 weeks) - Dependency resolution, registry +1. **Debugger** — IMPLEMENTED (`lib/phronesis/debugger.ex` + `debugger/repl.ex`) +2. **Profiler** — IMPLEMENTED (`lib/phronesis/profiler.ex` + `profiler/reporter.ex`) +3. **Documentation Generator** — IMPLEMENTED (`lib/phronesis/doc_generator.ex`) +4. **Package Manager** — IMPLEMENTED (`lib/phronesis/package_manager/`) +5. **REPL Enhancements** — partial (interactive REPL via the debugger) + +Newer work: the **reflexion** design layer (`lib/phronesis/reflexion/`) — see `docs/REFLEXION.adoc`. ## Commits @@ -252,7 +254,7 @@ Based on TOOLCHAIN-WISHLIST.md, the next sequential items are: ## Metrics -- **Overall Completion:** 50% → 60% +- **Overall Completion:** ~80% (LSP, debugger, profiler, doc-generator, package manager, reflexion all landed) - **Files Added:** 18 - **Lines Added:** 2,162 - **Tests:** 10/10 passing diff --git a/MAINTAINERS.adoc b/MAINTAINERS.adoc index becaa3e..aa23a55 100644 --- a/MAINTAINERS.adoc +++ b/MAINTAINERS.adoc @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: MPL-2.0 +// SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Maintainers :toc: preamble diff --git a/PALIMPSEST.adoc b/PALIMPSEST.adoc deleted file mode 100644 index 9660f13..0000000 --- a/PALIMPSEST.adoc +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) Jonathan D.A. Jewell -= Palimpsest License -:toc: -:toc-placement!: - -image:https://img.shields.io/badge/License-PMPL--1.0-blue.svg[License: PMPL-1.0,link="https://github.com/hyperpolymath/palimpsest-license"] -image:https://img.shields.io/badge/Philosophy-Palimpsest-indigo.svg[Palimpsest,link="https://github.com/hyperpolymath/palimpsest-license"] - -toc::[] - -== Legal Status - -This project is licensed under the **Palimpsest-MPL License 1.0 (PMPL-1.0)**. -For SPDX and tooling, use **MPL-2.0**. - -PMPL-1.0 incorporates the Mozilla Public License 2.0 by reference and adds -ethical-use, provenance, and lineage requirements. - -== What PMPL Adds - -* **Emotional Lineage** - preserve narrative intent and cultural context -* **Provenance Integrity** - retain attribution and lineage metadata -* **Ethical Use Constraints** - explicit consent for non-interpretive AI training -* **Quantum-Safe Provenance (optional)** - post-quantum signature support - -== How to Adopt - -1. Include the PMPL-1.0 license text in `LICENSE`. -2. Add SPDX headers to source files: - `SPDX-License-Identifier: MPL-2.0` -3. Add a Palimpsest badge to your README (see `assets/badges/` and `embed/license-blocks/`). - -== Versioning - -See `VERSIONING.adoc` for the release process and the "-or-later" model. -The current legal text is PMPL-1.0. - -== References - -* `legal/README.adoc` -* `assets/badges/README.md` -* `embed/license-blocks/README.md` diff --git a/README.adoc b/README.adoc index 5c16ece..75cedbc 100644 --- a/README.adoc +++ b/README.adoc @@ -1,12 +1,12 @@ -// SPDX-License-Identifier: MPL-2.0 +// SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Phronesis: A Provably Safe Language for Agentic Ethical Reasoning image:https://img.shields.io/badge/OpenSSF-Best_Practices-green?logo=openssourcesecurity[OpenSSF Best Practices,link="https://www.bestpractices.dev/en/projects/new?repo_url=https://github.com/hyperpolymath/phronesis"] -:license: PMPL-1.0 + Palimpsest v0.5 +:license: MPL-2.0 (code) and CC-BY-SA-4.0 (documentation) :author: Jonathan D. A. Jewell :version: Standard Candidate 1.0 -:repo: https://gitlab.com/hyperpolymath/phronesis +:repo: https://github.com/hyperpolymath/phronesis :toc: :toclevels: 3 :icons: font @@ -36,10 +36,10 @@ It fuses the precision of **Symbolic AI** with the adaptability of **neural netw == 🛡️ Intellectual Property & Licensing -Phronesis defines its IP across three layers, protected by a *dual-licensing* model: +Phronesis uses a *dual-licensing* model: -* **PMPL-1.0**: Ensures the runtime and compiler remain *free and open-source*, even in networked deployments. -* **Palimpsest v0.5**: Protects the *philosophical core* and *benchmark suite*, enabling open research while preserving ethical integrity. +* **MPL-2.0**: The runtime, compiler, and all source code — file-level copyleft that keeps the implementation free and open-source, even in networked deployments. +* **CC-BY-SA-4.0**: The documentation, philosophical core, and benchmark suite — open research and reuse under attribution and share-alike. === Claimable IP: Novel Design & Semantic Architecture @@ -95,11 +95,12 @@ Phronesis defines its IP across three layers, protected by a *dual-licensing* mo === Phased Bootstrap Strategy -. *Phase 1: Rapid Prototyping (Haskell)* - Validate type system and semantics via interpreter and REPL. +. *Phase 1: Reference Interpreter (Elixir/BEAM)* — implemented + Lexer, parser, type checker, interpreter, consensus, LSP, debugger, profiler, + and the reflexion design layer, all running on the BEAM. -. *Phase 2: Production Compiler (Rust/BEAM)* - Compile to BEAM VM bytecode (or WASM-on-BEAM) for performance and safety. +. *Phase 2: Production Compiler (Rust → WASM)* + Compile to WebAssembly via the `compiler/phronesis-ast` and `compiler/phronesis-wasm` crates. === Preferred Tooling @@ -108,7 +109,7 @@ Phronesis defines its IP across three layers, protected by a *dual-licensing* mo | Component | Tool / Language Preference | Development -| Haskell (Interpreter), Rust (Compiler) +| Elixir (reference implementation), Rust (WASM compiler) | Runtime | Erlang / Elixir (BEAM VM) @@ -129,17 +130,17 @@ Phronesis defines its IP across three layers, protected by a *dual-licensing* mo To begin contributing: -. Choose your repository name, Jonathan. . Clone the repo: + [source,bash] ---- - git clone git@gitlab.com:hyperpolymath/{REPOSITORY_NAME}.git + git clone git@github.com:hyperpolymath/phronesis.git ---- . Install dependencies: - - Rust toolchain - - Haskell GHC -. Run the benchmark suite: + - Erlang/OTP + Elixir (BEAM runtime) + - Rust toolchain (WASM compiler) + - `just` (task runner) +. Run the test suite with `just test`: *Passing all ethical scenarios is the definitive measure of correctness.* --- diff --git a/SPEC.core.a2ml b/SPEC.core.a2ml new file mode 120000 index 0000000..7f258b0 --- /dev/null +++ b/SPEC.core.a2ml @@ -0,0 +1 @@ +.machine_readable/SPEC.core.a2ml \ No newline at end of file diff --git a/SPEC.core.scm b/SPEC.core.scm deleted file mode 120000 index a4c339f..0000000 --- a/SPEC.core.scm +++ /dev/null @@ -1 +0,0 @@ -.machine_readable/SPEC.core.scm \ No newline at end of file diff --git a/TESTING-REPORT.adoc b/TESTING-REPORT.adoc index 49cc7fa..384abf4 100644 --- a/TESTING-REPORT.adoc +++ b/TESTING-REPORT.adoc @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: MPL-2.0 +// SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell // SPDX-FileCopyrightText: 2025 Phronesis Contributors = Phronesis Testing Report diff --git a/TESTING-REPORT.scm b/TESTING-REPORT.scm deleted file mode 100644 index bbacd43..0000000 --- a/TESTING-REPORT.scm +++ /dev/null @@ -1,345 +0,0 @@ -;; SPDX-License-Identifier: MPL-2.0 -;; SPDX-FileCopyrightText: 2025 Phronesis Contributors -;; -;; Phronesis Testing Report -;; Generated: 2025-12-29 -;; Generator: Claude Code (Anthropic) - -(define-module (phronesis testing-report) - #:export (testing-report - test-summary - issues-found - issues-fixed - test-results - recommendations)) - -;; ============================================================ -;; Testing Report - Phronesis Policy Language -;; ============================================================ - -(define testing-report - '((metadata - (report-date . "2025-12-29") - (report-version . "1.0.0") - (generator . "Claude Code") - (generator-model . "claude-opus-4-5-20251101") - (project . "phronesis") - (project-version . "0.1.0")) - - (environment - (operating-system . "Fedora Silverblue 43") - (kernel . "6.17.12-300.fc43.x86_64") - (platform . "linux x86_64") - (elixir-version . "1.17.3") - (erlang-otp-version . "26.2.5.16") - (mix-version . "1.17.3") - (runtime . "BEAM") - (test-container . "distrobox/fedora:41")))) - -;; ============================================================ -;; Test Summary -;; ============================================================ - -(define test-summary - '((overall-status . pass) - (total-tests . 162) - (tests-passed . 162) - (tests-failed . 0) - (doctests . 3) - (unit-tests . 159) - (execution-time-seconds . 0.8) - (total-time-seconds . 1.2))) - -;; ============================================================ -;; Issues Found During Testing -;; ============================================================ - -(define issues-found - '((issue-001 - (severity . error) - (type . compilation-error) - (file . "lib/phronesis/stdlib/rpki.ex") - (line . 187) - (description . "Missing Bitwise import for bitwise operators") - (error-message . "undefined function &&&/2, << += Phronesis Reflexion Layer +:toc: +:toclevels: 3 + +The *reflexion* layer is Phronesis's mechanism for _design self-relation_ — the +language treating its own semantics, obligations, and failures as objects of +judgement. It is deliberately spelled "reflexion", not "reflection": this is not +runtime introspection, it is the discipline by which the language maintains an +explicit, checkable account of _why_ its design is held valid, and re-evaluates +whether that account still coheres as the design changes. + +[NOTE] +==== +Reflexion is *advisory and gate-only*. It produces design obligations; it never +auto-mutates the AST, the compiler, or the runtime. Phronesis is not wise — but +it can keep a disciplined account of its own lack of wisdom. +==== + +== Motivation + +The ordinary toolchain compiles _programs_: + +---- +source .phr → parse/CST → core elaboration → type/effect/obligation/probability +checking → semantic IR → verification/proof obligations → runtime artefacts → +execution traces / reports / counterexamples +---- + +The reflexion layer sits _alongside_ that pipeline and compiles the language's +_design rationale_. Every important feature becomes an explicit claim +("Phronesis should require REPORT on map/territory divergence") supported by +evidence (semantic rationale, safety invariants, benchmark outcomes, proof +obligations, counterexamples, map-territory reports, human notes). The claims and +their warrant structure are a first-class artefact of the toolchain, not mere +documentation. + +== Pipeline + +---- +Build → Extract → Graph → Compare → Classify → Reevaluate → Gate +---- + +1. *Build* — compile/typecheck/verify the language and examples (ordinary toolchain). +2. *Extract* — `ClaimExtractor` turns artefacts into explicit `Claim`s. +3. *Graph* — `JudgementEvidenceGraph` records why each design decision is valid. +4. *Compare* — `InvariantPath` lifts justification paths; `Equivalence` compares them across versions. +5. *Classify* — the delta is labelled (see <>). +6. *Reevaluate* — `Revaluation` turns the classification into design obligations. +7. *Gate* — block / warn / permit a change to the language itself. + +== The three engines + +=== Claim Extractor + +`Phronesis.Reflexion.ClaimExtractor` walks a parsed program (the `Phronesis.AST` +tuples returned by `Phronesis.parse/1`) and emits claims of four kinds: +`:safety_preservation`, `:obligation_discharge`, `:evidence_for`, `:provenance`. + +The load-bearing case is the *map-territory mandate*: when a policy's action +subtree contains a `{:report, _}` node, the extractor emits a +`:safety_preservation` claim that the policy _preserves REPORT-adequacy_ +(epistemic safety) under the policy's match condition. + +Ingest from the compiler, the formal/proof layer (`formal/`, +`academic/formal-verification/`) and the benchmark suite (`bench/`) are declared +but stubbed today (`extract_from_compiler/1`, `extract_from_proofs/1`, +`extract_from_benchmarks/1` return `[]` with documented `TODO`s). + +=== Judgement-Evidence Graph + +`Phronesis.Reflexion.JudgementEvidenceGraph` is the language's memory of _why_ a +design is considered valid. Nodes are judgements; typed edges connect each to its +supporting evidence. The eight evidence kinds are: + +[cols="1,3"] +|=== +| Evidence kind | Meaning + +| `:semantic_rationale` | A design rationale / provenance link +| `:safety_invariant` | A static safety property +| `:benchmark_outcome` | Evidence from a benchmark run +| `:proof_obligation` | A discharged or pending proof obligation +| `:counterexample` | A case where omission caused unsafe behaviour +| `:map_territory_report` | A REPORT on map/territory divergence +| `:human_note` | A human design note +| `:failed_proof_obligation` | An obligation that did not discharge +|=== + +=== Invariant-Path Equivalence Engine + +`Phronesis.Reflexion.InvariantPath` models a _justification path_: + +---- +principle → construct → static_rule → proof_obligation → runtime_behaviour → audit_trace +---- + +`Phronesis.Reflexion.Equivalence` compares two paths and asks not "do both +type-check?" but "are these the same design claim under a harmless refactor, or +has the design's ethical/epistemic meaning changed?". + +[[taxonomy]] +== Classification taxonomy + +[cols="1,3,1"] +|=== +| Classification | Meaning | Gate + +| `:equivalent` | Identical justification; harmless refactor | permit +| `:refinement` | Additive detail within existing dimensions | permit +| `:strengthening` | Added a load-bearing justification | permit +| `:orthogonal_extension` | New, previously-absent dimension | warn +| `:weakening` | Dropped a load-bearing justification (e.g. a removed REPORT) | gate +| `:semantic_drift` | The governing principle changed | gate +| `:contradiction` | Runtime behaviour now contradicts the prior version | gate +| `:unresolved` | Could not be classified heuristically | gate +|=== + +The classifier is a deterministic heuristic; genuinely ambiguous cases fall to +`:unresolved` — the safe default, which is gated for human/tool review. + +== Supporting components + +=== Design Ledger + +`Phronesis.Reflexion.DesignLedger` is an append-only, SHA-256 hash-chained record +of design events (claims, classifications, obligations, notes). It is distinct +from the execution `Phronesis.Trace`: the trace records the run of a single +decision; the ledger records design events about the language across versions. A +ledger entry may _reference_ a trace id as evidence, but never embeds or replaces +traces. The hash chain makes the ledger tamper-evident. + +=== Revaluation + +`Phronesis.Reflexion.Revaluation` maps a classification to a gate verdict +(`:permit` / `:warn` / `:gate`) and any `Phronesis.Reflexion.DesignObligation`s. +For a weakening it emits the canonical obligation with three resolutions: _prove +the property is still preserved_, _mark as an intentional documented shift_, or +_reject the change_. + +== Integration points + +* `Phronesis.AST` — the claim source of truth (`ClaimExtractor` walks its tuples). +* `Phronesis.Trace` — execution evidence; referenced by, never merged into, the ledger. +* `Phronesis.Analyzer` / `Phronesis.Compiler` — future evidence sources (stubbed). +* `formal/` (TLA+) and `academic/formal-verification/` — proof obligations (stubbed). +* `bench/` — benchmark evidence (stubbed). + +== Non-goals + +* *Does not auto-mutate semantics.* Reflexion gates, warns, or permits — it never + silently changes the AST, compiler, or runtime. +* *Not a runtime supervisor.* It is a called library (like `Phronesis.Analyzer`), + not a supervised process. +* *Heuristic now, formal later.* Semantic equivalence via the proof layer is a + documented future hardening; until then ambiguous deltas are `:unresolved`. +* *Does not touch licences or provenance.* + +== Usage + +[source,elixir] +---- +{:ok, result} = Phronesis.Reflexion.review(v1_source, v2_source) +result.gate # :permit | :warn | :gate +result.obligations # [%Phronesis.Reflexion.DesignObligation{...}] +result.ledger # %Phronesis.Reflexion.DesignLedger{} (hash-chained) +---- + +---- +just reflexion-test # run the reflexion test suite +just reflexion-demo # demo: drop a REPORT mandate and watch it get gated +---- + +== Status + +[cols="2,1,3"] +|=== +| Component | Status | Note + +| Claim extraction (AST) | works | REPORT → REPORT-adequacy safety claim +| Judgement-evidence graph | works | in-memory, serialisable +| Invariant path | works | combined-per-subject and from-JEG +| Equivalence engine | works (heuristic) | 8-way classifier +| Design ledger | works | append-only, SHA-256 hash chain +| Revaluation | works | classification → gate + obligations +| Compiler / proof / benchmark ingest | stubbed | documented `TODO`s +| Formal semantic equivalence | stubbed | falls to `:unresolved` +|=== diff --git a/lib/phronesis/reflexion.ex b/lib/phronesis/reflexion.ex new file mode 100644 index 0000000..b124130 --- /dev/null +++ b/lib/phronesis/reflexion.ex @@ -0,0 +1,144 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion do + @moduledoc """ + Phronesis's reflexive design layer — *design self-relation*, not runtime reflection. + + The ordinary toolchain (parser → elaboration → type/effect/obligation checking → + verification → runtime/reporting) compiles *programs*. The reflexion layer sits + alongside it and compiles the language's *design rationale*: it turns toolchain + artefacts into explicit claims, records why a design is held valid in a + judgement-evidence graph, compares justification-paths across versions, and + emits design obligations that gate changes to the language itself. + + Pipeline: **Build → Extract → Graph → Compare → Classify → Reevaluate → Gate.** + + It never auto-mutates semantics; the strongest thing it does is *gate* a change + and require an explicit resolution. See `docs/REFLEXION.adoc` for the design. + + ## Example + + {:ok, result} = Phronesis.Reflexion.review(v1_source, v2_source) + result.gate #=> :permit | :warn | :gate + result.obligations #=> [%Phronesis.Reflexion.DesignObligation{...}] + """ + + alias Phronesis.Reflexion.{ + ClaimExtractor, + DesignLedger, + DesignObligation, + Equivalence, + InvariantPath, + JudgementEvidenceGraph, + Revaluation + } + + @type review :: %{ + gate: Revaluation.gate(), + deltas: [{String.t(), Equivalence.classification(), Revaluation.gate()}], + obligations: [DesignObligation.t()], + ledger: DesignLedger.t() + } + + @doc """ + Run the full reflexion pipeline over two source versions of a policy program. + + For every decision (policy) present in both versions, it lifts the combined + justification path, classifies the delta, revaluates it into a gate + any + obligations, and records the outcome in an append-only design ledger. The + overall gate is the most severe per-decision gate. + """ + @spec review(String.t(), String.t()) :: {:ok, review()} | {:error, term()} + def review(old_source, new_source) when is_binary(old_source) and is_binary(new_source) do + with {:ok, old_claims} <- ClaimExtractor.extract_from_source(old_source), + {:ok, new_claims} <- ClaimExtractor.extract_from_source(new_source) do + subjects = common_subjects(old_claims, new_claims) + + {gate, obligations, ledger, deltas} = + Enum.reduce(subjects, {:permit, [], DesignLedger.new(), []}, fn subject, + {gate_acc, obs_acc, ledger, + deltas_acc} -> + old_path = InvariantPath.from_claims(old_claims, subject) + new_path = InvariantPath.from_claims(new_claims, subject) + delta = Equivalence.compare(old_path, new_path) + {gate, obligations} = Revaluation.revaluate(delta, subject) + + ledger = + ledger + |> DesignLedger.append(:classification, Equivalence.to_map(delta), decision_id: subject) + |> append_obligations(obligations, subject) + + {merge_gate(gate_acc, gate), obs_acc ++ obligations, ledger, + deltas_acc ++ [{subject, delta.classification, gate}]} + end) + + {:ok, %{gate: gate, deltas: deltas, obligations: obligations, ledger: ledger}} + end + end + + @doc "Build the judgement-evidence graph for a single source version." + @spec graph(String.t()) :: {:ok, JudgementEvidenceGraph.t()} | {:error, term()} + def graph(source) when is_binary(source) do + with {:ok, claims} <- ClaimExtractor.extract_from_source(source) do + {:ok, JudgementEvidenceGraph.from_claims(claims)} + end + end + + @doc """ + Demonstrate the pipeline: take a policy that uses the `REPORT` map-territory + mandate, drop it in a second version, and show the resulting gate + obligation + + tamper-evident ledger. Used by the `just reflexion-demo` recipe. + """ + @spec demo() :: review() + def demo do + v1 = """ + POLICY warning_alert: + severity >= 70 AND severity < 90 + THEN REPORT("Warning level severity") + PRIORITY: 200 + EXPIRES: never + CREATED_BY: monitoring + """ + + v2 = String.replace(v1, ~s|REPORT("Warning level severity")|, ~s|ACCEPT("Warning level severity")|) + + {:ok, result} = review(v1, v2) + + IO.puts("Reflexion review — overall gate: #{result.gate}") + + Enum.each(result.deltas, fn {subject, classification, gate} -> + IO.puts(" #{subject}: #{classification} -> #{gate}") + end) + + Enum.each(result.obligations, fn o -> + IO.puts(" obligation [#{o.classification}] #{o.statement}") + Enum.each(o.options, fn opt -> IO.puts(" • #{opt}") end) + end) + + integrity = DesignLedger.verify(result.ledger) + IO.puts(" ledger: #{length(DesignLedger.entries(result.ledger))} entries, integrity #{inspect(integrity)}") + + result + end + + defp append_obligations(ledger, obligations, subject) do + Enum.reduce(obligations, ledger, fn obligation, ledger -> + DesignLedger.append(ledger, :obligation, DesignObligation.to_map(obligation), decision_id: subject) + end) + end + + defp common_subjects(old_claims, new_claims) do + old_subjects = old_claims |> Enum.map(& &1.subject) |> MapSet.new() + new_subjects = new_claims |> Enum.map(& &1.subject) |> MapSet.new() + + old_subjects |> MapSet.intersection(new_subjects) |> MapSet.to_list() |> Enum.sort() + end + + defp merge_gate(:gate, _), do: :gate + defp merge_gate(_, :gate), do: :gate + defp merge_gate(:warn, _), do: :warn + defp merge_gate(_, :warn), do: :warn + defp merge_gate(_, _), do: :permit +end diff --git a/lib/phronesis/reflexion/claim.ex b/lib/phronesis/reflexion/claim.ex new file mode 100644 index 0000000..d741116 --- /dev/null +++ b/lib/phronesis/reflexion/claim.ex @@ -0,0 +1,120 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.Claim do + @moduledoc """ + An explicit, first-class *claim* extracted from a Phronesis design artefact. + + The reflexion layer turns implicit design decisions into explicit claims so the + language can reason about *why* a design is considered valid. A claim is a small + subject–predicate–object record with the conditions under which it holds and a + pointer to the evidence source it was derived from. + + Claim kinds (mirroring the toolchain discussion): + + * `:safety_preservation` — "rule/feature R preserves safety property S under conditions C" + * `:obligation_discharge` — "feature F exists to discharge obligation O" + * `:evidence_for` — "artefact E is evidence for judgement J" + * `:provenance` — "symbol/feature originates from source" + """ + + @type kind :: :safety_preservation | :obligation_discharge | :evidence_for | :provenance + @type source :: {:ast | :compiler | :proof | :benchmark | :human, term()} + @type confidence :: :asserted | :derived | :stub + + @type t :: %__MODULE__{ + id: String.t(), + kind: kind(), + subject: String.t(), + predicate: String.t(), + object: String.t(), + conditions: [String.t()], + source: source(), + confidence: confidence(), + metadata: map() + } + + defstruct id: nil, + kind: :provenance, + subject: "", + predicate: "", + object: "", + conditions: [], + source: {:ast, nil}, + confidence: :derived, + metadata: %{} + + @doc """ + Build a claim from a keyword list of fields. An `:id` is generated if absent. + """ + @spec new(keyword()) :: t() + def new(fields) when is_list(fields) do + struct!(__MODULE__, Keyword.put_new_lazy(fields, :id, &generate_id/0)) + end + + @doc "A claim that `subject` preserves safety `property` under `conditions`." + @spec safety_preservation(String.t(), String.t(), [String.t()], keyword()) :: t() + def safety_preservation(subject, property, conditions, opts \\ []) do + new( + [ + kind: :safety_preservation, + subject: subject, + predicate: "preserves", + object: property, + conditions: conditions + ] ++ opts + ) + end + + @doc "A claim that `feature` exists to discharge `obligation`." + @spec obligation_discharge(String.t(), String.t(), keyword()) :: t() + def obligation_discharge(feature, obligation, opts \\ []) do + new( + [kind: :obligation_discharge, subject: feature, predicate: "discharges", object: obligation] ++ + opts + ) + end + + @doc "A claim that `evidence` supports `judgement`." + @spec evidence_for(String.t(), String.t(), keyword()) :: t() + def evidence_for(evidence, judgement, opts \\ []) do + new( + [kind: :evidence_for, subject: evidence, predicate: "is-evidence-for", object: judgement] ++ + opts + ) + end + + @doc "A provenance claim: `subject` originates from `origin`." + @spec provenance(String.t(), String.t(), keyword()) :: t() + def provenance(subject, origin, opts \\ []) do + new([kind: :provenance, subject: subject, predicate: "originates-from", object: origin] ++ opts) + end + + @doc "A JSON-serialisable map (same idiom as `Phronesis.Trace.to_map/1`)." + @spec to_map(t()) :: map() + def to_map(%__MODULE__{} = c) do + %{ + id: c.id, + kind: c.kind, + subject: c.subject, + predicate: c.predicate, + object: c.object, + conditions: c.conditions, + source: source_to_map(c.source), + confidence: c.confidence, + metadata: c.metadata + } + end + + @doc "Generate a unique claim id (mirrors `Phronesis.Trace`'s id strategy)." + @spec generate_id() :: String.t() + def generate_id, do: :crypto.strong_rand_bytes(8) |> Base.encode16(case: :lower) + + defp source_to_map({tag, detail}), do: %{tag: tag, detail: detail_to_string(detail)} + + defp detail_to_string(nil), do: nil + defp detail_to_string(d) when is_binary(d), do: d + defp detail_to_string(d) when is_atom(d), do: Atom.to_string(d) + defp detail_to_string(d), do: inspect(d) +end diff --git a/lib/phronesis/reflexion/claim_extractor.ex b/lib/phronesis/reflexion/claim_extractor.ex new file mode 100644 index 0000000..e3774b7 --- /dev/null +++ b/lib/phronesis/reflexion/claim_extractor.ex @@ -0,0 +1,146 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.ClaimExtractor do + @moduledoc """ + Turns Phronesis toolchain artefacts into explicit `Phronesis.Reflexion.Claim`s. + + Day one this walks a *parsed program* — exactly what `Phronesis.parse/1` returns + (`{:ok, [declaration()]}` where declarations are `Phronesis.AST` tuples). The + load-bearing case is the map-territory mandate: when a policy's action subtree + contains a `{:report, _}` node, the extractor emits a `:safety_preservation` + claim that the policy preserves *REPORT-adequacy* (epistemic safety) under the + policy's match condition. + + Ingest from the compiler, the formal/proof layer, and the benchmark suite are + declared but stubbed (returning `[]` with a documented `TODO`) so the rest of + the pipeline runs end-to-end today. + """ + + alias Phronesis.Reflexion.Claim + + @doc "Parse `source` and extract claims. Propagates parse errors." + @spec extract_from_source(String.t()) :: {:ok, [Claim.t()]} | {:error, term()} + def extract_from_source(source) when is_binary(source) do + case Phronesis.parse(source) do + {:ok, program} -> {:ok, extract(program)} + {:error, _} = err -> err + end + end + + @doc "Extract claims from a parsed program (a list of `Phronesis.AST` declarations)." + @spec extract([tuple()] | {:ok, [tuple()]}) :: [Claim.t()] + def extract({:ok, program}), do: extract(program) + + def extract(program) when is_list(program) do + Enum.flat_map(program, &claims_for_declaration/1) + end + + @doc "TODO: ingest claims from compiler artefacts (`.phrc` / `Phronesis.Compiler`)." + @spec extract_from_compiler(term()) :: [Claim.t()] + def extract_from_compiler(_artifacts), do: [] + + @doc "TODO: ingest proof obligations from `formal/` and `academic/formal-verification/`." + @spec extract_from_proofs(term()) :: [Claim.t()] + def extract_from_proofs(_paths), do: [] + + @doc "TODO: ingest benchmark outcomes from `bench/` as evidence claims." + @spec extract_from_benchmarks(term()) :: [Claim.t()] + def extract_from_benchmarks(_results), do: [] + + @doc "Human-readable rendering of an AST expression (used for path/claim labels)." + @spec describe_expr(term()) :: String.t() + def describe_expr({:literal, _type, value}), do: inspect(value) + def describe_expr({:identifier, name}), do: name + def describe_expr({:comparison, op, l, r}), do: "#{describe_expr(l)} #{op} #{describe_expr(r)}" + def describe_expr({:binary_op, op, l, r}), do: "#{describe_expr(l)} #{op} #{describe_expr(r)}" + def describe_expr({:unary_op, op, operand}), do: "#{op} #{describe_expr(operand)}" + def describe_expr({:module_call, path, _args}), do: "#{Enum.join(path, ".")}(...)" + def describe_expr(other), do: inspect(other) + + # --- per-declaration extraction -------------------------------------------- + + defp claims_for_declaration({:const, name, expr}) do + [ + Claim.provenance("const #{name}", describe_expr(expr), + source: {:ast, :const}, + confidence: :asserted + ) + ] + end + + defp claims_for_declaration({:import, path, _alias}) do + [ + Claim.provenance("import #{Enum.join(path, ".")}", "external module", + source: {:ast, :import}, + confidence: :asserted + ) + ] + end + + defp claims_for_declaration({:policy, name, condition, action, _metadata}) do + subject = "policy #{name}" + condition_label = describe_expr(condition) + + discharge = + Claim.obligation_discharge(subject, "decision-completeness", + source: {:ast, :policy}, + confidence: :asserted, + conditions: [condition_label] + ) + + [discharge] ++ report_claims(subject, condition_label, action) ++ decision_claims(subject, action) + end + + defp claims_for_declaration(_other), do: [] + + defp report_claims(subject, condition_label, action) do + if contains_report?(action) do + [ + Claim.safety_preservation(subject, "REPORT-adequacy", [condition_label], + source: {:ast, :report}, + confidence: :asserted, + metadata: %{property: "epistemic-safety", construct: "REPORT"} + ) + ] + else + [] + end + end + + defp decision_claims(subject, action) do + case decision_kind(action) do + nil -> + [] + + kind -> + [ + Claim.evidence_for(subject, "decision:#{kind}", + source: {:ast, kind}, + confidence: :asserted + ) + ] + end + end + + # walk an action subtree looking for a REPORT node (the map-territory mandate) + defp contains_report?({:report, _}), do: true + defp contains_report?({:block, actions}), do: Enum.any?(actions, &contains_report?/1) + + defp contains_report?({:conditional, _cond, then_action, else_action}) do + contains_report?(then_action) or (else_action != nil and contains_report?(else_action)) + end + + defp contains_report?(_), do: false + + defp decision_kind({:accept, _}), do: :accept + defp decision_kind({:reject, _}), do: :reject + defp decision_kind({:block, actions}), do: Enum.find_value(actions, &decision_kind/1) + + defp decision_kind({:conditional, _cond, then_action, else_action}) do + decision_kind(then_action) || if(else_action, do: decision_kind(else_action)) + end + + defp decision_kind(_), do: nil +end diff --git a/lib/phronesis/reflexion/design_ledger.ex b/lib/phronesis/reflexion/design_ledger.ex new file mode 100644 index 0000000..d22821f --- /dev/null +++ b/lib/phronesis/reflexion/design_ledger.ex @@ -0,0 +1,103 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.DesignLedger do + @moduledoc """ + An append-only, hash-chained record of design events. + + The design ledger is deliberately distinct from `Phronesis.Trace`: + + * `Phronesis.Trace` records the *execution* of a single decision at runtime + (eval / match / vote / action steps). + * `DesignLedger` records *design* events about the language itself across + versions (claims, classifications, obligations, notes). + + Entries are never mutated in place; each entry carries the SHA-256 hash of the + previous entry, giving a tamper-evident chain (satisfying the estate "SHA256+" + requirement). A ledger entry may *reference* a `Phronesis.Trace` id in its + payload (an execution trace used as evidence) but never embeds or replaces traces. + """ + + @type kind :: :claim | :classification | :obligation | :note + + @type entry :: %{ + id: String.t(), + at: DateTime.t(), + decision_id: String.t(), + kind: kind(), + payload: map(), + prev_hash: String.t() | nil, + hash: String.t() + } + + @type t :: %__MODULE__{entries: [entry()]} + + defstruct entries: [] + + @doc "An empty ledger." + @spec new() :: t() + def new, do: %__MODULE__{} + + @doc """ + Append an entry. The new entry's hash chains off the previous entry's hash, + so the ledger is tamper-evident and strictly append-only. + """ + @spec append(t(), kind(), map(), keyword()) :: t() + def append(%__MODULE__{entries: entries} = ledger, kind, payload, opts \\ []) do + prev_hash = + case entries do + [] -> nil + _ -> List.last(entries).hash + end + + decision_id = Keyword.get(opts, :decision_id, "—") + hash = compute_hash(prev_hash, kind, decision_id, payload) + + entry = %{ + id: :crypto.strong_rand_bytes(8) |> Base.encode16(case: :lower), + at: DateTime.utc_now(), + decision_id: decision_id, + kind: kind, + payload: payload, + prev_hash: prev_hash, + hash: hash + } + + %{ledger | entries: entries ++ [entry]} + end + + @doc "The entries, oldest first." + @spec entries(t()) :: [entry()] + def entries(%__MODULE__{entries: e}), do: e + + @doc "Verify the integrity of the hash chain." + @spec verify(t()) :: :ok | {:error, String.t()} + def verify(%__MODULE__{entries: entries}) do + entries + |> Enum.reduce_while({:ok, nil}, fn entry, {:ok, prev} -> + expected = compute_hash(prev, entry.kind, entry.decision_id, entry.payload) + + if expected == entry.hash and entry.prev_hash == prev do + {:cont, {:ok, entry.hash}} + else + {:halt, {:error, "ledger integrity broken at entry #{entry.id}"}} + end + end) + |> case do + {:ok, _} -> :ok + {:error, _} = err -> err + end + end + + @doc "A JSON-serialisable map." + @spec to_map(t()) :: map() + def to_map(%__MODULE__{entries: entries}) do + %{entries: Enum.map(entries, &Map.update!(&1, :at, fn at -> DateTime.to_iso8601(at) end))} + end + + defp compute_hash(prev_hash, kind, decision_id, payload) do + data = "#{prev_hash}|#{kind}|#{decision_id}|#{inspect(payload)}" + :crypto.hash(:sha256, data) |> Base.encode16(case: :lower) + end +end diff --git a/lib/phronesis/reflexion/design_obligation.ex b/lib/phronesis/reflexion/design_obligation.ex new file mode 100644 index 0000000..b57420c --- /dev/null +++ b/lib/phronesis/reflexion/design_obligation.ex @@ -0,0 +1,50 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.DesignObligation do + @moduledoc """ + A design obligation produced by the revaluation loop. + + Reflexion never silently mutates the language's semantics. When a change is + classified as risky (a weakening, a drift, a contradiction, or an unresolved + delta), the revaluation loop emits an *obligation* — a statement plus a small + menu of acceptable resolutions (typically: prove the property still holds, + mark the change as an intentional documented shift, or reject the change). + """ + + @type status :: :open | :discharged | :accepted_shift | :rejected + + @type t :: %__MODULE__{ + id: String.t(), + classification: atom(), + decision_id: String.t(), + statement: String.t(), + options: [String.t()], + status: status() + } + + defstruct id: nil, + classification: :unresolved, + decision_id: "—", + statement: "", + options: [], + status: :open + + @doc "Create an open obligation." + @spec new(atom(), String.t(), String.t(), [String.t()]) :: t() + def new(classification, decision_id, statement, options) do + %__MODULE__{ + id: :crypto.strong_rand_bytes(8) |> Base.encode16(case: :lower), + classification: classification, + decision_id: decision_id, + statement: statement, + options: options, + status: :open + } + end + + @doc "A JSON-serialisable map." + @spec to_map(t()) :: map() + def to_map(%__MODULE__{} = o), do: Map.from_struct(o) +end diff --git a/lib/phronesis/reflexion/equivalence.ex b/lib/phronesis/reflexion/equivalence.ex new file mode 100644 index 0000000..e99c5a1 --- /dev/null +++ b/lib/phronesis/reflexion/equivalence.ex @@ -0,0 +1,146 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.Equivalence do + @moduledoc """ + The Invariant-Path equivalence engine: compares two justification paths and + classifies the delta. + + A normal compiler can tell you whether both versions type-check; a proof + assistant whether each preserves a theorem. This engine asks a different + question — *are these the same design claim under a harmless refactor, or has + the design's ethical/epistemic meaning changed?* — and answers with one of: + + equivalent | refinement | weakening | strengthening + orthogonal_extension | semantic_drift | contradiction | unresolved + + The classifier is a deterministic heuristic over the path's `{stage, label}` + steps. Genuinely ambiguous cases fall to `:unresolved` — the safe default, + which the revaluation loop gates for human/tool review. (Formal semantic + equivalence via the proof layer is a documented future hardening.) + """ + + alias Phronesis.Reflexion.InvariantPath + + @type classification :: + :equivalent + | :refinement + | :weakening + | :strengthening + | :orthogonal_extension + | :semantic_drift + | :contradiction + | :unresolved + + @type delta :: %{ + classification: classification(), + added: [InvariantPath.step()], + removed: [InvariantPath.step()], + rationale: String.t() + } + + # stages whose removal weakens (or whose addition strengthens) the justification + @load_bearing [:proof_obligation, :static_rule, :audit_trace] + + @doc "Compare two justification paths (or two raw step lists)." + @spec compare(InvariantPath.t() | [InvariantPath.step()], InvariantPath.t() | [InvariantPath.step()]) :: + delta() + def compare(%InvariantPath{steps: old}, %InvariantPath{steps: new}), do: compare(old, new) + + def compare(old, new) when is_list(old) and is_list(new) do + old_set = MapSet.new(old) + new_set = MapSet.new(new) + removed = old_set |> MapSet.difference(new_set) |> MapSet.to_list() + added = new_set |> MapSet.difference(old_set) |> MapSet.to_list() + + classification = classify(old, new, removed, added) + %{classification: classification, added: added, removed: removed, rationale: rationale(classification)} + end + + @doc "A JSON-serialisable map of a delta." + @spec to_map(delta()) :: map() + def to_map(%{classification: c, added: added, removed: removed, rationale: r}) do + %{ + classification: c, + added: Enum.map(added, &step_to_map/1), + removed: Enum.map(removed, &step_to_map/1), + rationale: r + } + end + + # --- classification --------------------------------------------------------- + + defp classify(old, new, removed, added) do + cond do + removed == [] and added == [] -> :equivalent + principle_changed?(old, new) -> :semantic_drift + contradictory_runtime?(old, new) -> :contradiction + load_bearing?(removed) -> :weakening + removed == [] and load_bearing?(added) -> :strengthening + removed == [] and added != [] -> additive_kind(old, added) + true -> :unresolved + end + end + + defp additive_kind(old, added) do + old_stages = old |> stages() |> MapSet.new() + added_stages = added |> stages() |> MapSet.new() + + if MapSet.subset?(added_stages, old_stages) do + :refinement + else + :orthogonal_extension + end + end + + defp load_bearing?(steps), do: Enum.any?(stages(steps), &(&1 in @load_bearing)) + + defp stages(steps), do: Enum.map(steps, fn {stage, _label} -> stage end) + + defp principle_changed?(old, new) do + po = label_at(old, :principle) + pn = label_at(new, :principle) + po != nil and pn != nil and po != pn + end + + defp contradictory_runtime?(old, new) do + ro = label_at(old, :runtime_behaviour) + rn = label_at(new, :runtime_behaviour) + + with wo when not is_nil(wo) <- decision_word(ro), + wn when not is_nil(wn) <- decision_word(rn) do + wo != wn + else + _ -> false + end + end + + defp label_at(steps, target) do + Enum.find_value(steps, fn + {^target, label} -> label + _ -> nil + end) + end + + defp decision_word(nil), do: nil + + defp decision_word(label) when is_binary(label) do + cond do + String.contains?(label, "accept") -> :accept + String.contains?(label, "reject") -> :reject + true -> nil + end + end + + defp step_to_map({stage, label}), do: %{stage: stage, label: label} + + defp rationale(:equivalent), do: "Justification paths are identical; harmless under refactoring." + defp rationale(:refinement), do: "Additive detail within existing justification dimensions." + defp rationale(:strengthening), do: "Added a load-bearing justification (proof obligation / static rule / audit trace)." + defp rationale(:weakening), do: "Removed a load-bearing justification (e.g. a dropped REPORT / proof obligation)." + defp rationale(:orthogonal_extension), do: "Extended into a new, previously-absent justification dimension." + defp rationale(:semantic_drift), do: "The governing principle changed; design meaning may have drifted." + defp rationale(:contradiction), do: "Runtime behaviour now contradicts the prior version." + defp rationale(:unresolved), do: "Delta could not be classified heuristically; manual review required." +end diff --git a/lib/phronesis/reflexion/invariant_path.ex b/lib/phronesis/reflexion/invariant_path.ex new file mode 100644 index 0000000..e7fe2b5 --- /dev/null +++ b/lib/phronesis/reflexion/invariant_path.ex @@ -0,0 +1,105 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.InvariantPath do + @moduledoc """ + A *justification path* — the chain of reasoning behind a design decision: + + principle → construct → static_rule → proof_obligation → runtime_behaviour → audit_trace + + Invariant-Path is what the equivalence engine compares across versions. Rather + than comparing syntax trees or IR, it compares *paths of justification*, so it + can tell a harmless refactor from a change in the design's ethical/epistemic + meaning. + + Paths may be partial (not every decision touches every stage). Steps are + `{stage, label}` pairs and are kept ordered by the canonical stage order. + """ + + alias Phronesis.Reflexion.{Claim, JudgementEvidenceGraph} + + @type stage :: + :principle | :construct | :static_rule | :proof_obligation | :runtime_behaviour | :audit_trace + + @stages [:principle, :construct, :static_rule, :proof_obligation, :runtime_behaviour, :audit_trace] + + @type step :: {stage(), String.t()} + @type t :: %__MODULE__{decision_id: String.t() | nil, steps: [step()], meta: map()} + + defstruct decision_id: nil, steps: [], meta: %{} + + @doc "The canonical ordered list of stages." + @spec stages() :: [stage()] + def stages, do: @stages + + @doc "Rank of a stage in the canonical order (used for sorting/comparison)." + @spec stage_rank(stage()) :: non_neg_integer() + def stage_rank(stage), do: Enum.find_index(@stages, &(&1 == stage)) || length(@stages) + + @doc "Build a path for `decision_id` from explicit steps (filtered + ordered)." + @spec new(String.t(), [step()], map()) :: t() + def new(decision_id, steps, meta \\ %{}) do + %__MODULE__{decision_id: decision_id, steps: normalize_steps(steps), meta: meta} + end + + @doc """ + Build the combined justification path for `subject` from all of its claims. + + This is what the façade compares across two source versions: a policy that uses + a `REPORT` action carries an `:audit_trace` step (and `:construct` REPORT-adequacy); + dropping `REPORT` removes those load-bearing steps, which the equivalence engine + reads as a weakening. + """ + @spec from_claims([Claim.t()], String.t()) :: t() + def from_claims(claims, subject) when is_list(claims) do + relevant = Enum.filter(claims, &(&1.subject == subject)) + steps = [{:principle, "practical-judgement"}] ++ Enum.flat_map(relevant, &claim_steps/1) + new(subject, steps, %{subject: subject}) + end + + @doc "Lift a single judgement (and its evidence) from a JEG into a path." + @spec from_jeg(JudgementEvidenceGraph.t(), String.t()) :: t() + def from_jeg(%JudgementEvidenceGraph{} = g, judgement_id) do + judgement = Map.fetch!(g.judgements, judgement_id) + evidence = JudgementEvidenceGraph.evidence_for(g, judgement_id) + + steps = + [{:principle, principle_for(judgement)}, {:construct, judgement.label}] ++ + Enum.map(evidence, &evidence_step/1) + + new(judgement_id, steps, %{from: :jeg}) + end + + defp normalize_steps(steps) do + steps + |> Enum.filter(fn {stage, _label} -> stage in @stages end) + |> Enum.sort_by(fn {stage, _label} -> stage_rank(stage) end) + end + + defp claim_steps(%Claim{kind: :safety_preservation} = c) do + [{:construct, c.object}, {:audit_trace, "REPORT:" <> Enum.join(c.conditions, ",")}] + end + + defp claim_steps(%Claim{kind: :obligation_discharge} = c) do + [{:static_rule, c.object}, {:proof_obligation, Enum.join(c.conditions, ",")}] + end + + defp claim_steps(%Claim{kind: :evidence_for} = c) do + [{:runtime_behaviour, c.object}] + end + + defp claim_steps(%Claim{kind: :provenance}), do: [] + defp claim_steps(_), do: [] + + defp principle_for(%{kind: :safety_preservation}), do: "epistemic-safety" + defp principle_for(%{kind: :obligation_discharge}), do: "practical-judgement" + defp principle_for(_), do: "design-intent" + + defp evidence_step(%{kind: :map_territory_report, label: label}), do: {:audit_trace, label} + defp evidence_step(%{kind: :proof_obligation, label: label}), do: {:proof_obligation, label} + defp evidence_step(%{kind: :failed_proof_obligation, label: label}), do: {:proof_obligation, label} + defp evidence_step(%{kind: :benchmark_outcome, label: label}), do: {:runtime_behaviour, label} + defp evidence_step(%{kind: :safety_invariant, label: label}), do: {:static_rule, label} + defp evidence_step(%{label: label}), do: {:construct, label} +end diff --git a/lib/phronesis/reflexion/judgement_evidence_graph.ex b/lib/phronesis/reflexion/judgement_evidence_graph.ex new file mode 100644 index 0000000..f98bee4 --- /dev/null +++ b/lib/phronesis/reflexion/judgement_evidence_graph.ex @@ -0,0 +1,112 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.JudgementEvidenceGraph do + @moduledoc """ + The language's memory of *why* a design is considered valid. + + Nodes are judgements; each judgement is linked by typed edges to the evidence + that supports it. The eight evidence kinds mirror the toolchain discussion: + semantic rationale, safety invariant, benchmark outcome, proof obligation, + counterexample, map-territory report, human note, and failed proof obligation. + + This is an in-memory graph built from extracted claims (`from_claims/1`); it is + a first-class artefact of the toolchain, not merely documentation. + """ + + alias Phronesis.Reflexion.Claim + + @type evidence_kind :: + :semantic_rationale + | :safety_invariant + | :benchmark_outcome + | :proof_obligation + | :counterexample + | :map_territory_report + | :human_note + | :failed_proof_obligation + + @type judgement :: %{id: String.t(), label: String.t(), claim_id: String.t() | nil, kind: atom()} + @type evidence :: %{id: String.t(), kind: evidence_kind(), label: String.t()} + @type edge :: %{from: String.t(), to: String.t(), kind: evidence_kind()} + + @type t :: %__MODULE__{ + judgements: %{optional(String.t()) => judgement()}, + evidence: %{optional(String.t()) => evidence()}, + edges: [edge()], + meta: map() + } + + defstruct judgements: %{}, evidence: %{}, edges: [], meta: %{} + + @doc "An empty graph." + @spec new() :: t() + def new, do: %__MODULE__{} + + @doc "Add a judgement node; returns the updated graph and the node id." + @spec add_judgement(t(), String.t(), keyword()) :: {t(), String.t()} + def add_judgement(%__MODULE__{} = g, label, opts \\ []) do + id = Keyword.get(opts, :id, gen("j")) + + judgement = %{ + id: id, + label: label, + claim_id: Keyword.get(opts, :claim_id), + kind: Keyword.get(opts, :kind, :judgement) + } + + {%{g | judgements: Map.put(g.judgements, id, judgement)}, id} + end + + @doc "Attach a typed piece of evidence to a judgement; returns the graph and evidence id." + @spec add_evidence(t(), String.t(), evidence_kind(), String.t()) :: {t(), String.t()} + def add_evidence(%__MODULE__{} = g, judgement_id, kind, label) do + eid = gen("e") + evidence = %{id: eid, kind: kind, label: label} + edge = %{from: judgement_id, to: eid, kind: kind} + + {%{g | evidence: Map.put(g.evidence, eid, evidence), edges: g.edges ++ [edge]}, eid} + end + + @doc "Build a graph from a list of claims (one judgement + one typed evidence edge each)." + @spec from_claims([Claim.t()]) :: t() + def from_claims(claims) when is_list(claims) do + Enum.reduce(claims, new(), fn claim, g -> + {g, jid} = add_judgement(g, judgement_label(claim), claim_id: claim.id, kind: claim.kind) + {g, _eid} = add_evidence(g, jid, evidence_kind_for(claim), evidence_label(claim)) + g + end) + end + + @doc "The evidence attached to a judgement." + @spec evidence_for(t(), String.t()) :: [evidence()] + def evidence_for(%__MODULE__{} = g, judgement_id) do + g.edges + |> Enum.filter(&(&1.from == judgement_id)) + |> Enum.map(&Map.fetch!(g.evidence, &1.to)) + end + + @doc "A JSON-serialisable map." + @spec to_map(t()) :: map() + def to_map(%__MODULE__{} = g) do + %{ + judgements: Map.values(g.judgements), + evidence: Map.values(g.evidence), + edges: g.edges, + meta: g.meta + } + end + + defp judgement_label(%Claim{} = c), do: "#{c.subject} #{c.predicate} #{c.object}" + defp evidence_label(%Claim{} = c), do: "claim:#{c.id} (#{c.confidence})" + + # map a claim kind onto the evidence kind that supports its judgement + defp evidence_kind_for(%Claim{kind: :safety_preservation}), do: :map_territory_report + defp evidence_kind_for(%Claim{kind: :obligation_discharge}), do: :proof_obligation + defp evidence_kind_for(%Claim{kind: :evidence_for}), do: :benchmark_outcome + defp evidence_kind_for(%Claim{kind: :provenance}), do: :semantic_rationale + defp evidence_kind_for(_), do: :human_note + + defp gen(prefix), do: prefix <> "_" <> (:crypto.strong_rand_bytes(6) |> Base.encode16(case: :lower)) +end diff --git a/lib/phronesis/reflexion/revaluation.ex b/lib/phronesis/reflexion/revaluation.ex new file mode 100644 index 0000000..c6eb076 --- /dev/null +++ b/lib/phronesis/reflexion/revaluation.ex @@ -0,0 +1,97 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.Revaluation do + @moduledoc """ + The design revaluation loop. + + It consumes an equivalence classification and decides what it means for the + language: a gate verdict (`:permit` / `:warn` / `:gate`) plus any design + obligations. Crucially it produces **data only** — it never mutates an AST, + compiler output, or runtime configuration. Phronesis does not silently change + its own semantics; it maintains a disciplined account of proposed changes and + forces risky ones through an explicit obligation. + """ + + alias Phronesis.Reflexion.{DesignObligation, Equivalence} + + @type gate :: :permit | :warn | :gate + + @doc """ + Map a classification delta to a gate verdict and obligations. + + * `:equivalent` / `:refinement` / `:strengthening` → `:permit` (no obligation) + * `:orthogonal_extension` → `:warn` (informational obligation) + * `:weakening` / `:semantic_drift` / `:contradiction` / `:unresolved` → `:gate` (obligation) + """ + @spec revaluate(Equivalence.delta(), String.t()) :: {gate(), [DesignObligation.t()]} + def revaluate(%{classification: classification} = delta, decision_id) do + case classification do + :equivalent -> {:permit, []} + :refinement -> {:permit, []} + :strengthening -> {:permit, []} + :orthogonal_extension -> {:warn, [obligation(classification, decision_id, delta)]} + :weakening -> {:gate, [obligation(classification, decision_id, delta)]} + :semantic_drift -> {:gate, [obligation(classification, decision_id, delta)]} + :contradiction -> {:gate, [obligation(classification, decision_id, delta)]} + :unresolved -> {:gate, [obligation(classification, decision_id, delta)]} + end + end + + defp obligation(:weakening, decision_id, delta) do + DesignObligation.new( + :weakening, + decision_id, + statement(delta, "Change to #{decision_id} weakens a load-bearing justification (e.g. a dropped REPORT / proof obligation)."), + [ + "prove the weakened property is still preserved", + "mark as an intentional, documented design shift", + "reject the change" + ] + ) + end + + defp obligation(:semantic_drift, decision_id, delta) do + DesignObligation.new( + :semantic_drift, + decision_id, + statement(delta, "The governing principle of #{decision_id} changed; the design's meaning may have drifted."), + [ + "prove the new principle subsumes the old", + "mark as an intentional philosophical shift", + "reject the change" + ] + ) + end + + defp obligation(:contradiction, decision_id, delta) do + DesignObligation.new( + :contradiction, + decision_id, + statement(delta, "The runtime behaviour of #{decision_id} now contradicts the prior version."), + ["resolve the contradiction", "reject the change"] + ) + end + + defp obligation(:orthogonal_extension, decision_id, delta) do + DesignObligation.new( + :orthogonal_extension, + decision_id, + statement(delta, "#{decision_id} gained an orthogonal extension; confirm it does not interact with existing guarantees."), + ["confirm independence", "fold into an existing judgement"] + ) + end + + defp obligation(:unresolved, decision_id, delta) do + DesignObligation.new( + :unresolved, + decision_id, + statement(delta, "The change to #{decision_id} could not be classified; manual review is required."), + ["classify manually", "supply formal evidence", "reject the change"] + ) + end + + defp statement(%{rationale: r}, prefix) when is_binary(r) and r != "", do: prefix <> " (" <> r <> ")" + defp statement(_delta, prefix), do: prefix +end diff --git a/spec/README.adoc b/spec/README.adoc index a26b7d2..799ff6b 100644 --- a/spec/README.adoc +++ b/spec/README.adoc @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: MPL-2.0 +// SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell // @taxonomy: spec/index = phronesis — Specification Directory diff --git a/test/reflexion/claim_extractor_test.exs b/test/reflexion/claim_extractor_test.exs new file mode 100644 index 0000000..c251944 --- /dev/null +++ b/test/reflexion/claim_extractor_test.exs @@ -0,0 +1,51 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.ClaimExtractorTest do + use ExUnit.Case, async: true + + alias Phronesis.Reflexion.ClaimExtractor + + @report_policy """ + POLICY warning_alert: + severity >= 70 + THEN REPORT("Warning level severity") + PRIORITY: 200 + EXPIRES: never + CREATED_BY: monitoring + """ + + @const_only "CONST threshold = 50\n" + + test "a policy whose action uses REPORT yields a REPORT-adequacy safety claim" do + {:ok, claims} = ClaimExtractor.extract_from_source(@report_policy) + + safety = Enum.filter(claims, &(&1.kind == :safety_preservation)) + assert [claim] = safety + assert claim.object == "REPORT-adequacy" + assert claim.subject == "policy warning_alert" + assert claim.predicate == "preserves" + # the match condition is carried as the condition under which the property holds + assert claim.conditions != [] + end + + test "a const-only program yields provenance claims and no safety claims" do + {:ok, claims} = ClaimExtractor.extract_from_source(@const_only) + + assert Enum.any?(claims, &(&1.kind == :provenance and &1.subject == "const threshold")) + refute Enum.any?(claims, &(&1.kind == :safety_preservation)) + end + + test "a non-REPORT policy yields an obligation-discharge claim but no safety claim" do + src = String.replace(@report_policy, ~s|REPORT("Warning level severity")|, ~s|ACCEPT("ok")|) + {:ok, claims} = ClaimExtractor.extract_from_source(src) + + assert Enum.any?(claims, &(&1.kind == :obligation_discharge)) + refute Enum.any?(claims, &(&1.kind == :safety_preservation)) + end + + test "parse errors propagate" do + assert {:error, _} = ClaimExtractor.extract_from_source("this is not phronesis") + end +end diff --git a/test/reflexion/design_ledger_test.exs b/test/reflexion/design_ledger_test.exs new file mode 100644 index 0000000..aa9d42e --- /dev/null +++ b/test/reflexion/design_ledger_test.exs @@ -0,0 +1,45 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.DesignLedgerTest do + use ExUnit.Case, async: true + + alias Phronesis.Reflexion.DesignLedger + + test "append is monotonic and never mutates prior entries" do + ledger = DesignLedger.new() + l1 = DesignLedger.append(ledger, :note, %{n: 1}) + [first] = DesignLedger.entries(l1) + l2 = DesignLedger.append(l1, :note, %{n: 2}) + + assert length(DesignLedger.entries(l2)) == 2 + # the original first entry is unchanged + assert hd(DesignLedger.entries(l2)) == first + end + + test "each entry's hash chains off the previous entry" do + ledger = + DesignLedger.new() + |> DesignLedger.append(:note, %{n: 1}) + |> DesignLedger.append(:note, %{n: 2}) + + [e1, e2] = DesignLedger.entries(ledger) + assert e1.prev_hash == nil + assert e2.prev_hash == e1.hash + assert e1.hash != e2.hash + assert DesignLedger.verify(ledger) == :ok + end + + test "tampering with a payload breaks integrity verification" do + ledger = + DesignLedger.new() + |> DesignLedger.append(:note, %{n: 1}) + |> DesignLedger.append(:note, %{n: 2}) + + [e1, e2] = DesignLedger.entries(ledger) + tampered = %{ledger | entries: [%{e1 | payload: %{n: 999}}, e2]} + + assert {:error, _} = DesignLedger.verify(tampered) + end +end diff --git a/test/reflexion/equivalence_test.exs b/test/reflexion/equivalence_test.exs new file mode 100644 index 0000000..d609ffb --- /dev/null +++ b/test/reflexion/equivalence_test.exs @@ -0,0 +1,67 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.EquivalenceTest do + use ExUnit.Case, async: true + + alias Phronesis.Reflexion.Equivalence + + defp classify(old, new), do: Equivalence.compare(old, new).classification + + test "identical paths are equivalent" do + path = [{:principle, "practical-judgement"}, {:static_rule, "decision-completeness"}] + assert classify(path, path) == :equivalent + end + + test "a changed principle is semantic drift" do + old = [{:principle, "epistemic-safety"}, {:static_rule, "r"}] + new = [{:principle, "practical-judgement"}, {:static_rule, "r"}] + assert classify(old, new) == :semantic_drift + end + + test "accept-vs-reject runtime is a contradiction" do + old = [{:principle, "p"}, {:runtime_behaviour, "decision:accept"}] + new = [{:principle, "p"}, {:runtime_behaviour, "decision:reject"}] + assert classify(old, new) == :contradiction + end + + test "dropping a load-bearing step is a weakening" do + old = [{:principle, "p"}, {:proof_obligation, "o"}, {:audit_trace, "REPORT:x"}] + new = [{:principle, "p"}, {:proof_obligation, "o"}] + assert classify(old, new) == :weakening + end + + test "adding a load-bearing step is a strengthening" do + old = [{:principle, "p"}] + new = [{:principle, "p"}, {:proof_obligation, "o"}] + assert classify(old, new) == :strengthening + end + + test "additive detail within existing dimensions is a refinement" do + old = [{:principle, "p"}, {:construct, "a"}] + new = [{:principle, "p"}, {:construct, "a"}, {:construct, "b"}] + assert classify(old, new) == :refinement + end + + test "extending into a new non-load-bearing dimension is an orthogonal extension" do + old = [{:principle, "p"}, {:construct, "a"}] + new = [{:principle, "p"}, {:construct, "a"}, {:runtime_behaviour, "x"}] + assert classify(old, new) == :orthogonal_extension + end + + test "an unclassifiable add+remove falls to unresolved" do + old = [{:principle, "p"}, {:construct, "a"}] + new = [{:principle, "p"}, {:runtime_behaviour, "x"}] + assert classify(old, new) == :unresolved + end + + test "delta carries added/removed steps and a rationale, and is serialisable" do + old = [{:principle, "p"}, {:proof_obligation, "o"}] + new = [{:principle, "p"}] + delta = Equivalence.compare(old, new) + assert {:proof_obligation, "o"} in delta.removed + assert is_binary(delta.rationale) + assert %{classification: :weakening} = Equivalence.to_map(delta) + end +end diff --git a/test/reflexion/invariant_path_test.exs b/test/reflexion/invariant_path_test.exs new file mode 100644 index 0000000..9a4a6ec --- /dev/null +++ b/test/reflexion/invariant_path_test.exs @@ -0,0 +1,45 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.InvariantPathTest do + use ExUnit.Case, async: true + + alias Phronesis.Reflexion.{Claim, ClaimExtractor, InvariantPath, JudgementEvidenceGraph} + + @report_policy """ + POLICY warning_alert: + severity >= 70 + THEN REPORT("Warning level severity") + PRIORITY: 200 + EXPIRES: never + CREATED_BY: monitoring + """ + + test "steps are filtered to known stages and ordered canonically" do + path = InvariantPath.new("d", [{:audit_trace, "a"}, {:principle, "p"}, {:bogus, "x"}]) + stages = Enum.map(path.steps, fn {stage, _} -> stage end) + assert stages == [:principle, :audit_trace] + end + + test "a REPORT policy's combined path carries an audit_trace step" do + {:ok, claims} = ClaimExtractor.extract_from_source(@report_policy) + path = InvariantPath.from_claims(claims, "policy warning_alert") + stages = Enum.map(path.steps, fn {stage, _} -> stage end) + + assert :audit_trace in stages + assert :principle in stages + end + + test "from_jeg lifts a judgement and its evidence into an ordered path" do + claims = [Claim.safety_preservation("policy p", "REPORT-adequacy", ["x > 1"])] + g = JudgementEvidenceGraph.from_claims(claims) + [jid] = Map.keys(g.judgements) + + path = InvariantPath.from_jeg(g, jid) + stages = Enum.map(path.steps, fn {stage, _} -> stage end) + + assert List.first(stages) == :principle + assert :audit_trace in stages + end +end diff --git a/test/reflexion/judgement_evidence_graph_test.exs b/test/reflexion/judgement_evidence_graph_test.exs new file mode 100644 index 0000000..f0352c7 --- /dev/null +++ b/test/reflexion/judgement_evidence_graph_test.exs @@ -0,0 +1,50 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.JudgementEvidenceGraphTest do + use ExUnit.Case, async: true + + alias Phronesis.Reflexion.{Claim, ClaimExtractor, JudgementEvidenceGraph} + + @report_policy """ + POLICY warning_alert: + severity >= 70 + THEN REPORT("Warning level severity") + PRIORITY: 200 + EXPIRES: never + CREATED_BY: monitoring + """ + + test "from_claims makes one judgement and one typed evidence edge per claim" do + claims = [ + Claim.obligation_discharge("policy p", "decision-completeness"), + Claim.safety_preservation("policy p", "REPORT-adequacy", ["x > 1"]) + ] + + g = JudgementEvidenceGraph.from_claims(claims) + + assert map_size(g.judgements) == 2 + assert map_size(g.evidence) == 2 + assert length(g.edges) == 2 + end + + test "a REPORT (safety) claim produces a map_territory_report edge" do + {:ok, claims} = ClaimExtractor.extract_from_source(@report_policy) + g = JudgementEvidenceGraph.from_claims(claims) + + assert Enum.any?(g.edges, &(&1.kind == :map_territory_report)) + end + + test "evidence_for returns the evidence attached to a judgement" do + {g, jid} = JudgementEvidenceGraph.add_judgement(JudgementEvidenceGraph.new(), "j") + {g, _eid} = JudgementEvidenceGraph.add_evidence(g, jid, :human_note, "note") + + assert [%{kind: :human_note, label: "note"}] = JudgementEvidenceGraph.evidence_for(g, jid) + end + + test "to_map is serialisable" do + g = JudgementEvidenceGraph.from_claims([Claim.provenance("const x", "1")]) + assert %{judgements: [_], evidence: [_], edges: [_]} = JudgementEvidenceGraph.to_map(g) + end +end diff --git a/test/reflexion/revaluation_test.exs b/test/reflexion/revaluation_test.exs new file mode 100644 index 0000000..36d138f --- /dev/null +++ b/test/reflexion/revaluation_test.exs @@ -0,0 +1,36 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.Reflexion.RevaluationTest do + use ExUnit.Case, async: true + + alias Phronesis.Reflexion.Revaluation + + defp delta(classification), do: %{classification: classification, added: [], removed: [], rationale: ""} + + test "weakening gates and emits an obligation with the three resolutions" do + {gate, [obligation]} = Revaluation.revaluate(delta(:weakening), "policy p") + assert gate == :gate + assert obligation.classification == :weakening + assert length(obligation.options) == 3 + assert "reject the change" in obligation.options + end + + test "refinement permits with no obligation" do + assert {:permit, []} = Revaluation.revaluate(delta(:refinement), "policy p") + end + + test "strengthening and equivalent both permit" do + assert {:permit, []} = Revaluation.revaluate(delta(:strengthening), "policy p") + assert {:permit, []} = Revaluation.revaluate(delta(:equivalent), "policy p") + end + + test "orthogonal extension warns" do + assert {:warn, [_]} = Revaluation.revaluate(delta(:orthogonal_extension), "policy p") + end + + test "unresolved gates for manual review" do + assert {:gate, [_]} = Revaluation.revaluate(delta(:unresolved), "policy p") + end +end diff --git a/test/reflexion_test.exs b/test/reflexion_test.exs new file mode 100644 index 0000000..e18e87c --- /dev/null +++ b/test/reflexion_test.exs @@ -0,0 +1,51 @@ +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) Jonathan D.A. Jewell +# SPDX-FileCopyrightText: 2025 Phronesis Contributors + +defmodule Phronesis.ReflexionTest do + use ExUnit.Case, async: true + + alias Phronesis.Reflexion + alias Phronesis.Reflexion.DesignLedger + + @v1 """ + POLICY warning_alert: + severity >= 70 AND severity < 90 + THEN REPORT("Warning level severity") + PRIORITY: 200 + EXPIRES: never + CREATED_BY: monitoring + """ + + # identical to @v1 but the REPORT map-territory mandate is dropped for a plain ACCEPT + @v2 String.replace(@v1, ~s|REPORT("Warning level severity")|, ~s|ACCEPT("Warning level severity")|) + + test "an identical program permits with no obligations" do + {:ok, result} = Reflexion.review(@v1, @v1) + assert result.gate == :permit + assert result.obligations == [] + end + + test "dropping a REPORT mandate is weakened and gated, with an obligation and ledger entries" do + {:ok, result} = Reflexion.review(@v1, @v2) + + assert result.gate == :gate + assert [{"policy warning_alert", :weakening, :gate}] = result.deltas + assert [obligation] = result.obligations + assert obligation.classification == :weakening + + # the change is recorded in a tamper-evident, append-only ledger + assert DesignLedger.verify(result.ledger) == :ok + assert length(DesignLedger.entries(result.ledger)) >= 2 + end + + test "graph/1 builds a judgement-evidence graph for a source version" do + {:ok, graph} = Reflexion.graph(@v1) + assert map_size(graph.judgements) > 0 + assert Enum.any?(graph.edges, &(&1.kind == :map_territory_report)) + end + + test "parse errors propagate from review/2" do + assert {:error, _} = Reflexion.review("not phronesis", @v1) + end +end diff --git a/verification/README.adoc b/verification/README.adoc index 9390fbc..6137a6e 100644 --- a/verification/README.adoc +++ b/verification/README.adoc @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: MPL-2.0 +// SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell // @taxonomy: verification/index = phronesis — Verification Directory