From c042f05a6064d46723b068e4c1f0ea962808e51a Mon Sep 17 00:00:00 2001 From: Sumer Vaid Date: Sun, 1 Nov 2026 17:43:21 -0500 Subject: [PATCH 1/3] Add Explorer, reader commands, installer and guides for readers without Lean --- .devcontainer/devcontainer.json | 13 + .github/workflows/ci.yml | 26 ++ .github/workflows/pages.yml | 40 +++ .gitignore | 4 + CHANGELOG.md | 17 + CONTRIBUTING.md | 4 + Makefile | 18 +- README.md | 26 +- config/curation.yaml | 74 +++++ docs/commands.md | 45 +++ docs/getting-started.md | 62 ++++ docs/glossary.md | 24 ++ docs/reading-results.md | 53 ++++ install.sh | 115 +++++++ pipeline/README.md | 2 +- pipeline/lemma/__init__.py | 2 +- pipeline/lemma/cli.py | 309 +++++++++++++++++- pipeline/lemma/doctor.py | 86 +++++ pipeline/lemma/draft.py | 159 ++++++++++ pipeline/lemma/explore.py | 312 ++++++++++++++++++ pipeline/lemma/site.py | 222 +++++++++++++ pipeline/lemma/site_assets/app.js | 440 ++++++++++++++++++++++++++ pipeline/lemma/site_assets/body.html | 15 + pipeline/lemma/site_assets/head.html | 9 + pipeline/lemma/site_assets/overlap.js | 51 +++ pipeline/lemma/site_assets/styles.css | 110 +++++++ pipeline/pyproject.toml | 4 +- pipeline/tests/test_explore.py | 291 +++++++++++++++++ 28 files changed, 2521 insertions(+), 12 deletions(-) create mode 100644 .devcontainer/devcontainer.json create mode 100644 .github/workflows/pages.yml create mode 100644 config/curation.yaml create mode 100644 docs/commands.md create mode 100644 docs/getting-started.md create mode 100644 docs/glossary.md create mode 100644 docs/reading-results.md create mode 100755 install.sh create mode 100644 pipeline/lemma/doctor.py create mode 100644 pipeline/lemma/draft.py create mode 100644 pipeline/lemma/explore.py create mode 100644 pipeline/lemma/site.py create mode 100644 pipeline/lemma/site_assets/app.js create mode 100644 pipeline/lemma/site_assets/body.html create mode 100644 pipeline/lemma/site_assets/head.html create mode 100644 pipeline/lemma/site_assets/overlap.js create mode 100644 pipeline/lemma/site_assets/styles.css create mode 100644 pipeline/tests/test_explore.py diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..8387d84 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,13 @@ +{ + "name": "Lemma", + "image": "mcr.microsoft.com/devcontainers/base:ubuntu-24.04", + "postCreateCommand": "./install.sh", + "remoteEnv": { + "PATH": "${containerEnv:PATH}:/home/vscode/.local/bin:/home/vscode/.elan/bin" + }, + "customizations": { + "vscode": { + "extensions": ["leanprover.lean4"] + } + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b177f27..626db1b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,6 +43,9 @@ jobs: - name: Lint run: cd pipeline && ruff check . && ruff format --check . + - name: Build the Explorer + run: cd pipeline && python -m lemma.cli --root .. site + - name: Python tests run: cd pipeline && python -m pytest -q @@ -52,3 +55,26 @@ jobs: python -m lemma.cli --root .. formalize --offline python -m lemma.cli --root .. report --no-build git -C .. diff --stat -- README.md reports/library.md || true + + installer: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + + - name: One-line install from a pipe, as a new user runs the script + env: + LEMMA_REPO_URL: file://${{ github.workspace }} + LEMMA_HOME: ${{ runner.temp }}/lemma + run: bash < install.sh + + - name: Commands work after install + run: | + "$HOME/.local/bin/lemma" doctor + "$HOME/.local/bin/lemma" tour + "$HOME/.local/bin/lemma" compare Exhaustion Vigor + "$HOME/.local/bin/lemma" new --name "ci draft" --definition "A check of the draft path" \ + --citation "CI" --category AffectiveState --level Individual --horizon Weekly --part Energy diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..fa12c14 --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,40 @@ +name: explorer + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: pages + cancel-in-progress: true + +jobs: + deploy: + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Build the Explorer from the checked-in reports + run: | + python -m pip install -e pipeline + python -m lemma.cli --root . site + + - uses: actions/upload-pages-artifact@v3 + with: + path: site + + - id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index 168c8cc..d267628 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,7 @@ dist/ .env reports/_scratch/ .DS_Store + +# Generated by lemma new and lemma site +drafts/ +site/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b2a6cf..7b42e2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ All notable changes to the kernel, the primitive vocabulary and the pipeline. The kernel follows semantic versioning (`KERNEL_VERSION` in `Lemma/Kernel/Basic.lean`). +## Pipeline 0.2.0 (unreleased) + +The kernel, the library, the checks and every report stay as released in 0.1.0. + +### Access for readers without Lean +- Lemma Explorer: a generated, self-contained web page for browsing constructs, comparing definitions, reading disagreements and the agenda, drafting a construct, and downloading tables as CSV. +- Commands `lemma doctor`, `tour`, `find`, `show`, `compare`, `new`, `try`, `site`. Compiler replies are explained in plain language. +- `install.sh` for one-step setup on macOS and Linux, with a Codespaces configuration for every other platform. + +### Curation +- `config/curation.yaml` holds the findings, cautions and starting collections, with counts filled from the compiler report. +- Guides under `docs/`: getting started, reading the results, glossary, commands. + +### Assurance +- Tests hold the plain-language overlap rule to every overlap the compiler reports, the browser logic to the Python logic, and a generated draft to a real compile. +- CI runs the installer on Ubuntu and macOS. + ## Kernel 0.1.0, library 0.1.0, pipeline 0.1.0 (2026-11-01) Initial release accompanying the Stage 1 proposal. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2db1dec..ffd5139 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,6 +4,10 @@ Modeled on the Mathlib contribution guidelines: small, reviewed additions to a shared library, with conventions enforced by the compiler where the compiler can, and by review where it cannot. +## Contributing without Lean + +Draft a construct in the [Explorer](https://sumervaid.github.io/lemma/#draft) or with `lemma new`, then open a [discussion](https://github.com/sumervaid/lemma/discussions/1) with the source paper. Corrections to a reading of a source are as valuable as new entries, and they need no code. + ## What a contribution is - **A theory module** under `Lemma/Theories/.lean`: the constructs a diff --git a/Makefile b/Makefile index 98b2991..f41c122 100644 --- a/Makefile +++ b/Makefile @@ -12,9 +12,13 @@ endif PY ?= python3 LEMMA ?= $(PY) -m lemma.cli -.PHONY: help install build test test-lean test-python lint format formalize check score distinct verify report clean +.PHONY: help setup doctor tour site install build test test-lean test-python lint format formalize check score distinct verify report clean help: + @echo "make setup one-step setup: Python environment, Lean, compiled library" + @echo "make doctor state what works on this machine" + @echo "make tour the curated findings" + @echo "make site build the Explorer at site/index.html" @echo "make install install the Python pipeline (editable) and dev tools" @echo "make build lake build (kernel, library, theories, accepted generated modules)" @echo "make test lake build LemmaTests (#guard_msgs) + pytest + ruff" @@ -25,6 +29,18 @@ help: @echo "make verify write a review sheet for human verification" @echo "make report formalize + check + score + distinct + precision; refreshes README numbers" +setup: + ./install.sh + +doctor: + cd pipeline && $(LEMMA) --root .. doctor + +tour: + cd pipeline && $(LEMMA) --root .. tour + +site: + cd pipeline && $(LEMMA) --root .. site + install: $(PY) -m pip install -e pipeline[dev] diff --git a/README.md b/README.md index f9be123..467f51c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Lemma [![CI](https://github.com/sumervaid/lemma/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/sumervaid/lemma/actions/workflows/ci.yml) +[![Explorer](https://img.shields.io/badge/Explorer-open_in_browser-0b5cad.svg)](https://sumervaid.github.io/lemma/) [![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE) [![Lean 4.15.0](https://img.shields.io/badge/Lean-4.15.0-blue.svg)](lean-toolchain) @@ -8,9 +9,25 @@ A type system for organizational constructs and propositions, built on Lean 4, w Sumer Vaid, Harvard Business School. Apache-2.0. Research prototype accompanying the Stage 1 proposal to the *Organization Science* special issue on AI-Enabled Frontiers in Organizational Science. +## Start here + +| Goal | Route | Setup | +|---|---|---| +| Browse constructs, compare definitions, test an idea | [Lemma Explorer](https://sumervaid.github.io/lemma/) | None | +| Run the compiler with no local install | [Open a Codespace](https://codespaces.new/sumervaid/lemma) | A GitHub account | +| Run the compiler on a laptop | One line below, for macOS or Linux | About five minutes | +| Reproduce the proposal | [For reviewers](#for-reviewers) | Lean 4.15.0 with Python 3.11 or later | + +```bash +curl -fsSL https://raw.githubusercontent.com/sumervaid/lemma/main/install.sh | bash +lemma tour +``` + +[Getting started](docs/getting-started.md) walks through each route with no prior knowledge of Lean. [Reading the results](docs/reading-results.md) explains each output, with [a glossary](docs/glossary.md) and [a command list](docs/commands.md). + ## For reviewers -Lean 4.15.0 with Python 3.11 or later must be on the path. +Lean 4.15.0 with Python 3.11 or later must be on the path. `make setup` installs both inside the repository. ```bash make install @@ -103,6 +120,8 @@ To run the pipeline with a live model instead of fixtures, point `LEMMA_LLM_BASE ## How to add a construct or a theory +Scholars without Lean can draft in the [Explorer](https://sumervaid.github.io/lemma/#draft) or with `lemma new`, then open a [discussion](https://github.com/sumervaid/lemma/discussions/1). The rest of this section is for direct contributions. + One theory per module under `Lemma/Theories/`, one construct per definition, a citation docstring on every definition, and an overlap declaration for every overlap the compiler reports. `CONTRIBUTING.md` has the checklist. ```lean @@ -172,10 +191,13 @@ Lemma/Library/ primitives and base categories Lemma/Theories/ pilot library, one module per theory Lemma/Generated/ accepted machine formalizations (pipeline output) LemmaTests/ #guard_msgs tests pinning compiler messages -pipeline/ Python package `lemma` (formalize, check, score, distinct, verify) +pipeline/ Python package `lemma`, including the Explorer and the reader commands +install.sh one-step setup for macOS and Linux +docs/ guides for readers with no Lean background fixtures/ paper summaries, fixture formalizations, correlations.csv bibliography/ curated source list counted by `lemma check` config/scoring.yaml scorer weights +config/curation.yaml findings and collections shown by `lemma tour` and the Explorer reports/ generated reports (library, agenda, distinctness, papers, failed modules) verification/ human review sheets and precision scripts/report.lean the Lean script that dumps the registries diff --git a/config/curation.yaml b/config/curation.yaml new file mode 100644 index 0000000..db83ed4 --- /dev/null +++ b/config/curation.yaml @@ -0,0 +1,74 @@ +# Curated reading of the pilot library, shared by `lemma tour` and the Explorer. +# Counts appear as {placeholders} filled from reports/library.json, so a count +# here can never drift from the compiler. A test resolves every name below. + +status: >- + Pilot status. Curated entries are the author's readings of {papers_curated_sources} sources. + Pipeline entries come from hand-written fixtures, with no model run. + Correlations on file are placeholder or recalled values. Precision is unmeasured. + +findings: + - title: Exhaustion and vigor reduce to one part + body: >- + The library defines both from Energy at one scope, so the compiler reports identical + definitions. The library then records a declared distinction with a stated reason. + caution: The part assignment is the author's reading. The compiler reports what the definitions contain. + compare: [Burnout.Exhaustion, Engagement.Vigor] + - title: Cynicism and dedication show the same pattern + body: >- + Both read identification with work at one scope. The field debated this bipolarity for a + decade, while the compiler surfaces the pair at the moment of definition. + caution: A shared part leaves the empirical question open. Correlations on file await a source check. + compare: [Burnout.Cynicism, Engagement.Dedication] + - title: Two burnout models disagree on one path + body: >- + The sequential model asserts cynicism precedes reduced efficacy. The process model asserts + a null relation at the same scope and boundary. + caution: The reading of Leiter 1993 behind the null awaits a check against the source. + view: disagreements + - title: Challenge demands pull task performance two ways + body: >- + Composition through exhaustion implies a negative path. A direct claim in the library + states a positive relation, which restates the challenge-stressor paradox as a type conflict. + caution: An implied sign describes one mediating path, separate from any total effect. + view: disagreements + - title: "{implied_untested} implied pairs lack a direct claim in the library" + body: >- + Chaining existing claims yields pairs no library entry states. The agenda ranks them for + attention alongside registered claims resting on thin evidence. + caution: Absence from the library differs from absence from the literature. Many pairs may already have tests. + view: agenda + - title: "{formalization_failures} of {papers_pipeline_total} pipeline papers were refused" + body: >- + Each refusal names the missing piece, whether an absent part, an absent aggregation rule, + or a process theory lacking a measurement model. + caution: Hand-written fixtures produced these outcomes in order to exercise the pipeline. No model ran. + view: disagreements + +collections: + - title: Burnout and engagement + blurb: The bipolarity question, with facets side by side. + constructs: + - Burnout.Burnout + - Burnout.Exhaustion + - Burnout.Cynicism + - Burnout.ReducedEfficacy + - Engagement.Engagement + - Engagement.Vigor + - Engagement.Dedication + - Engagement.Absorption + - title: Energy across theories + blurb: Constructs from separate literatures resting on one part. + constructs: + - Thriving.Vitality + - Engagement.Vigor + - ShiromVigor.ShiromVigor + - Burnout.Exhaustion + - title: Demands and resources + blurb: Three vocabularies for strain. + constructs: + - JDR.JobDemands + - JDR.JobResources + - COR.Resources + - ERI.Effort + - ERI.Reward diff --git a/docs/commands.md b/docs/commands.md new file mode 100644 index 0000000..0f13f37 --- /dev/null +++ b/docs/commands.md @@ -0,0 +1,45 @@ +# Commands + +## For readers + +These commands read the checked-in reports. `new` and `try` also run the compiler when Lean is present. + +| Command | Purpose | +|---|---| +| `lemma` | Show a short menu | +| `lemma doctor` | State what works on this machine, with next steps | +| `lemma tour` | Print the curated findings with their cautions | +| `lemma find WORDS` | Search constructs, claims and parts | +| `lemma show NAME` | Print one construct in plain language | +| `lemma compare A B` | Set two constructs side by side | +| `lemma new` | Write a construct from plain answers, then check the draft | +| `lemma try FILE` | Check a draft file, with the compiler's reply explained | +| `lemma site --open` | Build the Explorer, then open the page in a browser | + +`lemma new` also takes every answer as a flag, for scripted use. Run `lemma new --help` for the list. + +## For maintainers + +| Command | Purpose | +|---|---| +| `lemma formalize` | Paper to module to compiler | +| `lemma check` | Compiler report at `reports/library.json` | +| `lemma score` | Verification agenda at `reports/agenda.md` | +| `lemma distinct` | Definitional against empirical distinctness | +| `lemma verify` | Review sheet, or precision from labelled sheets | +| `lemma report` | All reports, plus the README numbers | + +## Make targets + +| Target | Purpose | +|---|---| +| `make setup` | Run `install.sh` | +| `make install` | Install the pipeline into the active Python | +| `make build` | Compile the library | +| `make test` | Lean tests, Python tests, lint | +| `make report` | Regenerate every report | +| `make site` | Build the Explorer at `site/index.html` | + +## Curating the Explorer + +`config/curation.yaml` holds the findings, cautions and starting collections shown by `lemma tour` and the Explorer. Counts appear as placeholders filled from the compiler report. A test resolves every construct name in the file. diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..aa6da75 --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,62 @@ +# Getting started + +Lemma needs no programming background. Pick the route with the least setup for the task at hand. + +## Browse in a web browser + +Open the [Lemma Explorer](https://sumervaid.github.io/lemma/). Nothing needs installing. + +1. Select a tile in the table of parts to list every construct built on that part. +2. Open **Compare** to set two constructs side by side. +3. Open **Draft a construct** to describe an idea. The page lists every construct already using the same parts. +4. Open **Agenda** to see where a new study would teach the library the most. + +Tables on the Constructs, Claims and Agenda pages download as CSV files for Excel or R. + +## Run the compiler in a cloud workspace + +A free GitHub account is enough, and this route also suits Windows. + +1. Open [a new Codespace](https://codespaces.new/sumervaid/lemma), then select **Create codespace**. +2. Wait for setup to finish. The first start takes a few minutes. +3. In the terminal at the bottom of the window, type `lemma tour`. + +## Install on a laptop + +On macOS or Linux, open the Terminal app, paste this line, then press Return. + +```bash +curl -fsSL https://raw.githubusercontent.com/sumervaid/lemma/main/install.sh | bash +``` + +The script places Lemma in a folder named `lemma` in the home directory, along with the Python and Lean versions the project needs. The download is about 250 MB. To skip Lean for browsing alone, add `-s -- --browse-only` after `bash`. + +Run `lemma doctor` at any time to see what works on the machine. + +## First ten minutes + +```bash +lemma tour # the curated findings +lemma find trust # search constructs, claims, parts +lemma show Thriving # one construct in plain language +lemma compare Exhaustion Vigor # two constructs side by side +lemma new # answer a few questions, receive a checked draft +``` + +`lemma new` asks for a name, a definition, a citation, a category, a scope, then the parts. The draft lands in the `drafts` folder, and the compiler replies in plain language. + +## Next steps + +- [Reading the results](reading-results.md) explains each output. +- [Glossary](glossary.md) defines every term. +- [Commands](commands.md) lists every command. +- [Discussions](https://github.com/sumervaid/lemma/discussions) take proposals for a construct or a theory, with no code required. + +## When something goes wrong + +| Message | Fix | +|---|---| +| `lemma: command not found` | Close the terminal, open a new one, then try again. Otherwise add `export PATH="$HOME/.local/bin:$PATH"` to the shell profile. | +| `Compiled library` shows `add` in `lemma doctor` | Run `make build` inside the Lemma folder. | +| `Lean` shows `add` in `lemma doctor` | Run `./install.sh` inside the Lemma folder. | +| Setup stops partway | Run the same line again. Finished steps are skipped. The log is at `.lake/install.log`. | diff --git a/docs/glossary.md b/docs/glossary.md new file mode 100644 index 0000000..22fc366 --- /dev/null +++ b/docs/glossary.md @@ -0,0 +1,24 @@ +# Glossary + +| Term | Plain meaning | +|---|---| +| Aggregation rule | A registered way to move a construct up a level, such as a team mean of individual scores. | +| Claim | A typed statement linking two constructs, with a direction, a scope, an evidence kind and a citation. The code calls this a proposition. | +| Compiler | The program checking every definition and claim. Lemma runs the checks inside Lean. | +| Composition | Chaining two claims to imply a third. | +| Construct | A named concept written as a set of parts at one level with one horizon. | +| Curated entry | A definition or claim the author wrote from the cited source. | +| Declaration | A recorded decision on an overlap, with a reason. | +| Evidence kind | The design behind a claim, such as meta-analytic, longitudinal, cross-sectional, or none. | +| Fixture | A hand-written file standing in for model output, so the pipeline can run with no model. | +| Horizon | The time span a construct covers, such as daily, weekly, or static. | +| Kernel | The small set of construction rules everything reduces to. The kernel holds zero psychological content. | +| Lean | A proof assistant from mathematics, used here as the checking engine. Reading results requires zero knowledge of Lean. | +| Level | The unit of analysis, such as individual, team, or organization. | +| Module | One file holding one theory. | +| Part | A basic quantity such as energy or attention. The code calls this a primitive. | +| Pipeline | The software route from a paper to a draft module to the compiler. | +| Precision | The share of machine-drafted entries a human reviewer judges faithful to the source. Precision remains unmeasured in this release. | +| Reduction | The check confirming a construct unfolds entirely into registered parts. | +| Scope | A level paired with a horizon, such as Individual / Weekly. | +| Temporal rule | A registered way to move a construct to a longer horizon. | diff --git a/docs/reading-results.md b/docs/reading-results.md new file mode 100644 index 0000000..71e11d5 --- /dev/null +++ b/docs/reading-results.md @@ -0,0 +1,53 @@ +# Reading the results + +Every output answers a question about definitions and claims. None of them settles an empirical question. + +## Where each entry comes from + +| Label | Meaning | +|---|---| +| Curated | The author wrote the entry from the cited source. Fidelity to the source is itself a verification task. | +| Pipeline fixture | The entry comes from a hand-written file standing in for model output. No model produced any entry in this release. | + +## Overlap + +Two constructs overlap when they share a part at the same level and horizon. + +| Result | Meaning | +|---|---| +| Identical | Both use exactly the same parts. | +| Nested | Every part of one also belongs to the other. | +| Partial | They share some parts while each keeps parts of its own. | + +An overlap asks for a decision. A scholar records the pair as distinct, an alias, or a subtype, with a reason. A compiler result of identical can sit beside a recorded distinction, because parts carry no sign. Exhaustion reads low energy while vigor reads high energy. + +The result follows from the parts assigned to each definition, so a contested assignment makes for a contested overlap. + +## Disagreements + +| Result | Meaning | +|---|---| +| Direct contradiction | Two theories state opposing directions for one pair at one scope under one boundary condition. | +| Implied against direct | Chaining two claims implies a sign which a direct claim contradicts. | +| Conditional disagreement | Opposing directions appear under different boundary conditions. | +| Shape disagreement | One theory states a straight relation while another states a curve. | + +## Implied pairs + +Chaining `A → B` with `B → C` implies a relation from `A` to `C`. The reports mark a pair as `untested` when the library holds no direct claim on the pair. + +This label describes the library alone. The wider literature may hold many tests of the same pair, and a scan of that literature comes before any new study. An implied sign also describes one mediating path, separate from any total effect. + +## Agenda + +The scorer ranks candidates for attention. + +``` +score = 0.40 evidence weakness + 0.25 structural load + 0.25 disagreement + 0.10 implied +``` + +A high score marks a candidate for a closer look. The score says nothing about whether the claim holds. Weights live in `config/scoring.yaml`. + +## Correlations + +Each row in `fixtures/correlations.csv` carries a status. Placeholder values are illustrative. Recalled values were entered from memory. Neither should be cited until checked against the source. diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..880c51a --- /dev/null +++ b/install.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# One-step Lemma setup for macOS and Linux. +# +# curl -fsSL https://raw.githubusercontent.com/sumervaid/lemma/main/install.sh | bash +# +# Everything lands inside the Lemma folder, ~/.local/bin, ~/.elan and the uv cache. +# Options: --browse-only skips Lean, --dir PATH picks the folder. +set -euo pipefail + +REPO_URL="${LEMMA_REPO_URL:-https://github.com/sumervaid/lemma}" +DEST="${LEMMA_HOME:-$HOME/lemma}" +WITH_LEAN=1 + +while [ $# -gt 0 ]; do + case "$1" in + --browse-only) WITH_LEAN=0 ;; + --dir) shift; DEST="$1" ;; + -h|--help) sed -n '2,8p' "${BASH_SOURCE[0]:-/dev/null}"; exit 0 ;; + *) echo "Unknown option $1. Options are --browse-only and --dir PATH."; exit 2 ;; + esac + shift +done + +say() { printf '\n==> %s\n' "$1"; } +LOG="" +on_error() { + echo + echo "Setup stopped before finishing." + [ -n "$LOG" ] && [ -f "$LOG" ] && { echo "Last lines of $LOG:"; tail -20 "$LOG"; } + echo "Please report the message above at $REPO_URL/issues" + echo "The Explorer needs no setup: https://sumervaid.github.io/lemma/" +} +trap on_error ERR + +case "$(uname -s)" in + Darwin|Linux) ;; + *) + echo "This script supports macOS and Linux." + echo "On Windows, use a Codespace: https://codespaces.new/sumervaid/lemma" + exit 1 + ;; +esac + +command -v curl >/dev/null || { echo "curl is required. Install curl, then run this script again."; exit 1; } + +# Use the surrounding checkout when run from one. Otherwise fetch a copy. +HERE="$(cd "$(dirname "${BASH_SOURCE[0]:-/nonexistent}")" 2>/dev/null && pwd || true)" +if [ -n "$HERE" ] && [ -f "$HERE/lakefile.lean" ]; then + ROOT="$HERE" +elif [ -f "$DEST/lakefile.lean" ]; then + ROOT="$DEST" + say "Using the existing copy at $ROOT" +else + say "Downloading Lemma to $DEST" + if command -v git >/dev/null; then + git clone --quiet --depth 1 "$REPO_URL" "$DEST" + else + mkdir -p "$DEST" + curl -fsSL "$REPO_URL/archive/refs/heads/main.tar.gz" | tar -xz --strip-components=1 -C "$DEST" + fi + ROOT="$DEST" +fi +cd "$ROOT" +mkdir -p "$ROOT/.lake" +LOG="$ROOT/.lake/install.log" +: > "$LOG" + +export PATH="$HOME/.local/bin:$HOME/.elan/bin:$HOME/.cargo/bin:$PATH" + +say "Setting up Python" +if ! command -v uv >/dev/null; then + curl -LsSf https://astral.sh/uv/install.sh | env UV_NO_MODIFY_PATH=1 sh >>"$LOG" 2>&1 +fi +[ -x .venv/bin/python ] || uv venv --quiet --python 3.13 .venv +uv pip install --quiet --python .venv/bin/python -e "pipeline[dev]" + +if [ "$WITH_LEAN" = 1 ]; then + say "Setting up Lean, a download of about 250 MB on the first run" + if ! command -v lake >/dev/null; then + curl -fsSL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --no-modify-path --default-toolchain none >>"$LOG" 2>&1 + fi + say "Compiling the library, a minute or two on the first run" + lake build Lemma >>"$LOG" 2>&1 +fi + +say "Adding the lemma command" +LAUNCHER="$ROOT/.venv/bin/lemma-launch" +cat > "$LAUNCHER" <``. -Commands --------- +Commands for readers +-------------------- +doctor state what works on this machine +tour the curated findings +find search constructs, claims and parts +show one construct in plain language +compare two constructs side by side +new write a construct from plain answers, then check the draft +try check a draft file, with the compiler's reply explained +site build the browsable Explorer + +Commands for maintainers +------------------------ formalize paper(s) → Lemma module → compiler → reports/papers/.json check compiler over the whole library → reports/library.{json,md} score verification-priority scorer → reports/agenda.{md,json} @@ -15,15 +26,34 @@ import argparse import json import sys +import webbrowser from pathlib import Path -from .check import load_library, run_check, write_json +from .check import generated_modules, load_library, run_check, write_json from .config import LLMConfig, Paths, find_repo_root from .distinct import DEFAULT_THRESHOLD, classify, read_csv, render +from .doctor import render as render_doctor +from .doctor import run_checks +from .draft import CATEGORIES, HORIZONS, LEVELS, all_parts, parse_catalog, render_lean, submit, to_identifier +from .explore import ( + AmbiguousNameError, + Library, + UnknownNameError, + clean_doc, + describe_comparison, + describe_construct, + fill_counts, + format_claim, + load_curation, + part_label, + tail, + theory_name, +) from .formalize import formalize_paper from .lean import toolchain_available from .llm import FixtureProvider, OpenAICompatibleProvider from .score import load_scoring_config, render_agenda, score_library +from .site import build_site from .verify import all_sheets, compute_precision, sample_items, write_sheet @@ -32,6 +62,231 @@ def _paths(args: argparse.Namespace) -> Paths: return Paths(root) +START_TEXT = """Lemma checks organizational theory the way a compiler checks code. + +Explore the library + lemma tour the curated findings + lemma find energy search constructs, claims, parts + lemma show Thriving one construct in plain language + lemma compare Exhaustion Vigor two constructs side by side + lemma site --open the Explorer, in a browser + +Check a new idea + lemma new answer a few questions, receive a checked draft + lemma try drafts/MyIdea.lean check a draft file + +Set up + lemma doctor state what works on this machine + +Every command, including the maintainer pipeline: lemma --help +""" + + +def _resolve(lib: Library, query: str): + try: + return lib.resolve(query) + except AmbiguousNameError as err: + print(f"{err.query} names several constructs. Pick one:", file=sys.stderr) + for option in err.options: + print(f" {option}", file=sys.stderr) + except UnknownNameError as err: + print(f"No construct is named {err.query}.", file=sys.stderr) + if err.suggestions: + print("Closest matches:", file=sys.stderr) + for option in err.suggestions: + print(f" {option}", file=sys.stderr) + else: + print("Search with: lemma find ", file=sys.stderr) + return None + + +def cmd_doctor(args: argparse.Namespace) -> int: + text, code = render_doctor(run_checks(_paths(args))) + print(text) + return code + + +def cmd_tour(args: argparse.Namespace) -> int: + paths = _paths(args) + lib = Library(paths) + curation = load_curation(paths) + print(fill_counts(curation["status"], lib.report)) + for finding in curation["findings"]: + print(f"\n{fill_counts(finding['title'], lib.report)}") + print(f" {fill_counts(finding['body'], lib.report)}") + print(f" Caution. {finding['caution']}") + if finding.get("compare"): + a, b = finding["compare"] + print(f" See: lemma compare {a} {b}") + return 0 + + +def cmd_find(args: argparse.Namespace) -> int: + lib = Library(_paths(args)) + query = " ".join(args.words) + constructs, claims, parts = lib.find_constructs(query), lib.find_claims(query), lib.find_parts(query) + if not (constructs or claims or parts): + print(f"No matches for {query}. Try one broader word.") + return 1 + if parts: + print("Parts") + for p in parts: + print(f" {tail(p['name']):18s} {clean_doc(p.get('doc', ''))[:90]}") + if constructs: + print(f"\nConstructs: {len(constructs)}") + for c in constructs[: args.limit]: + print(f" {theory_name(c['name'])}") + if claims: + print(f"\nClaims: {len(claims)}") + for p in claims[: args.limit]: + print(f" {format_claim(p)}") + print("\nFor detail: lemma show ") + return 0 + + +def cmd_show(args: argparse.Namespace) -> int: + lib = Library(_paths(args)) + construct = _resolve(lib, " ".join(args.name)) + if construct is None: + return 1 + print(describe_construct(lib, construct)) + return 0 + + +def cmd_compare(args: argparse.Namespace) -> int: + lib = Library(_paths(args)) + a, b = _resolve(lib, args.a), _resolve(lib, args.b) + if a is None or b is None: + return 1 + print(describe_comparison(lib.compare(a, b))) + return 0 + + +def _ask(prompt: str, default: str = "") -> str: + suffix = f" [{default}]" if default else "" + answer = input(f"{prompt}{suffix}: ").strip() + return answer or default + + +def _choose(prompt: str, options: list[str], labels: dict[str, str] | None = None, default: str = "") -> str: + print(prompt) + for i, option in enumerate(options, start=1): + print(f" {i:2d} {(labels or {}).get(option, option)}") + while True: + answer = _ask("Number", str(options.index(default) + 1) if default else "") + if answer.isdigit() and 1 <= int(answer) <= len(options): + return options[int(answer) - 1] + print(f"Enter a number from 1 to {len(options)}.") + + +def _labelled_parts(parts: list[str]) -> dict[str, str]: + return {p: part_label(p.split()[0], p.split()[1:]) for p in parts} + + +def _choose_parts(parts: list[str]) -> list[str]: + labels = _labelled_parts(parts) + print("Parts. Enter a word to search, a number to add, or a blank line to finish.") + chosen: list[str] = [] + shown = parts + while True: + for i, part in enumerate(shown, start=1): + print(f" {i:2d} {labels[part]}") + answer = _ask(f"Chosen so far: {len(chosen)}") + if not answer: + if chosen: + return chosen + print("A construct needs at least one part.") + elif answer.isdigit() and 1 <= int(answer) <= len(shown): + pick = shown[int(answer) - 1] + if pick not in chosen: + chosen.append(pick) + print(f"Added {labels[pick]}.") + shown = parts + else: + shown = [p for p in parts if answer.lower() in labels[p].lower()] or parts + + +def _report_submission(paths: Paths, file: Path, raw: bool) -> int: + if not toolchain_available(): + print(f"Wrote {file}.") + print("The compiler check needs Lean. Run ./install.sh, then: lemma try " + str(file)) + return 0 + ok, messages = submit(paths, file) + tones = {"problem": "Problem", "attention": "Attention", "note": "Note"} + for m in messages: + print(f"\n{tones[m.tone]}. {m.headline}") + print(f" {m.detail}") + if raw: + print(f" Compiler text, line {m.line}: {m.raw}") + print() + if ok: + attention = sum(m.tone == "attention" for m in messages) + print( + f"Compiled. {attention} overlap or disagreement messages call for a decision." + if attention + else "Compiled with nothing to resolve." + ) + else: + print("The draft did not compile. Each problem above names the fix.") + return 0 if ok else 1 + + +def cmd_new(args: argparse.Namespace) -> int: + paths = _paths(args) + catalog = parse_catalog((paths.root / "Lemma" / "Library" / "Primitives.lean").read_text(encoding="utf-8")) + parts = all_parts(catalog) + categories = list(CATEGORIES) + name = args.name or _ask("Construct name, for example work vitality") + try: + identifier = to_identifier(name) + except ValueError as err: + print(err, file=sys.stderr) + return 2 + definition = args.definition or _ask("One-sentence definition") + citation = args.citation or _ask("Citation with author, year, page") + category = args.category or _choose("Category", categories, CATEGORIES) + level = args.level or _choose("Level of analysis", LEVELS, default="Individual") + horizon = args.horizon or _choose("Time horizon", HORIZONS, default="Weekly") + chosen = args.part or _choose_parts(parts) + unknown = [p for p in chosen if p not in parts] + if unknown: + print(f"Unknown parts: {', '.join(unknown)}. Run lemma find to list parts.", file=sys.stderr) + return 2 + if category not in CATEGORIES or level not in LEVELS or horizon not in HORIZONS: + print( + f"Categories: {', '.join(categories)}. Levels: {', '.join(LEVELS)}. Horizons: {', '.join(HORIZONS)}.", + file=sys.stderr, + ) + return 2 + drafts = paths.root / "drafts" + drafts.mkdir(exist_ok=True) + file = drafts / f"{identifier}.lean" + file.write_text( + render_lean(identifier, definition, citation, category, level, horizon, chosen, generated_modules(paths)), + encoding="utf-8", + ) + print(f"\nWrote {file}") + return _report_submission(paths, file, args.raw) + + +def cmd_try(args: argparse.Namespace) -> int: + file = Path(args.file) + if not file.exists(): + print(f"No file at {file}.", file=sys.stderr) + return 2 + return _report_submission(_paths(args), file, args.raw) + + +def cmd_site(args: argparse.Namespace) -> int: + paths = _paths(args) + out = Path(args.out) if args.out else paths.root / "site" / "index.html" + build_site(paths, out) + print(f"Wrote {out}") + if args.open: + webbrowser.open(out.resolve().as_uri()) + return 0 + + def cmd_formalize(args: argparse.Namespace) -> int: paths = _paths(args) if not toolchain_available(): @@ -202,9 +457,50 @@ def cmd_report(args: argparse.Namespace) -> int: def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(prog="lemma", description="Lemma pipeline") + parser = argparse.ArgumentParser(prog="lemma", description="Check organizational theory with a compiler.") parser.add_argument("--root", help="repository root (default: auto-detect from cwd)") - sub = parser.add_subparsers(dest="command", required=True) + sub = parser.add_subparsers(dest="command") + + p = sub.add_parser("doctor", help="state what works on this machine") + p.set_defaults(func=cmd_doctor) + + p = sub.add_parser("tour", help="the curated findings") + p.set_defaults(func=cmd_tour) + + p = sub.add_parser("find", help="search constructs, claims and parts") + p.add_argument("words", nargs="+") + p.add_argument("--limit", type=int, default=15) + p.set_defaults(func=cmd_find) + + p = sub.add_parser("show", help="one construct in plain language") + p.add_argument("name", nargs="+") + p.set_defaults(func=cmd_show) + + p = sub.add_parser("compare", help="two constructs side by side") + p.add_argument("a") + p.add_argument("b") + p.set_defaults(func=cmd_compare) + + p = sub.add_parser("new", help="write a construct from plain answers, then check the draft") + p.add_argument("--name") + p.add_argument("--definition") + p.add_argument("--citation") + p.add_argument("--category", help=", ".join(CATEGORIES)) + p.add_argument("--level", help=", ".join(LEVELS)) + p.add_argument("--horizon", help=", ".join(HORIZONS)) + p.add_argument("--part", action="append", help="repeatable, for example --part Energy --part 'Attention Work'") + p.add_argument("--raw", action="store_true", help="also print the compiler's own text") + p.set_defaults(func=cmd_new) + + p = sub.add_parser("try", help="check a draft file, with the compiler's reply explained") + p.add_argument("file") + p.add_argument("--raw", action="store_true", help="also print the compiler's own text") + p.set_defaults(func=cmd_try) + + p = sub.add_parser("site", help="build the browsable Explorer") + p.add_argument("--out", help="output file (default: site/index.html)") + p.add_argument("--open", action="store_true", help="open the Explorer in a browser") + p.set_defaults(func=cmd_site) p = sub.add_parser("formalize", help="formalize papers into Lemma modules") p.add_argument("papers", nargs="*", help=".txt or .pdf files (default: fixtures/papers/*.txt)") @@ -241,6 +537,9 @@ def build_parser() -> argparse.ArgumentParser: def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) + if not args.command: + print(START_TEXT) + return 0 return int(args.func(args)) diff --git a/pipeline/lemma/doctor.py b/pipeline/lemma/doctor.py new file mode 100644 index 0000000..c267b1c --- /dev/null +++ b/pipeline/lemma/doctor.py @@ -0,0 +1,86 @@ +"""``lemma doctor``: state what works on this machine, with the next step for anything missing.""" + +from __future__ import annotations + +import re +import subprocess +import sys +from dataclasses import dataclass + +from .config import Paths +from .draft import library_built +from .lean import _env, toolchain_available + + +@dataclass +class Check: + name: str + ok: bool + detail: str + fix: str = "" + required: bool = True + + +def _lean_version() -> str: + try: + out = subprocess.run( + ["lean", "--version"], env=_env(), capture_output=True, text=True, timeout=120, check=False + ) + except OSError: + return "" + found = re.search(r"version (\d+\.\d+\.\d+)", out.stdout) + return found.group(1) if found else "" + + +def run_checks(paths: Paths) -> list[Check]: + version = ".".join(str(n) for n in sys.version_info[:3]) + wanted = (paths.root / "lean-toolchain").read_text(encoding="utf-8").strip().rsplit(":v", 1)[-1] + checks = [ + Check("Python 3.11 or later", sys.version_info >= (3, 11), f"found {version}", "Run ./install.sh"), + Check( + "Library reports", + (paths.reports / "library.json").exists(), + "reports/library.json", + "Download a fresh copy of the repository.", + ), + ] + has_lean = toolchain_available() + found = _lean_version() if has_lean else "" + checks.append( + Check( + f"Lean {wanted}", + found == wanted, + f"found {found}" if found else "absent", + "Run ./install.sh to add the checker. Browsing commands work meanwhile.", + required=False, + ) + ) + checks.append( + Check( + "Compiled library", + library_built(paths.root), + ".lake/build", + "Run make build. The first build takes a minute or two.", + required=False, + ) + ) + return checks + + +def render(checks: list[Check]) -> tuple[str, int]: + lines = ["Lemma doctor", ""] + for c in checks: + lines.append(f" {'ok ' if c.ok else 'add'} {c.name:24s} {c.detail}") + fixes = [c.fix for c in checks if not c.ok and c.fix] + required_ok = all(c.ok for c in checks if c.required) + full = all(c.ok for c in checks) + lines.append("") + if full: + lines.append("Ready. Every command works. Try lemma tour, lemma site --open, or lemma new.") + elif required_ok: + lines.append("Ready for browsing with lemma tour, lemma find, lemma show, lemma compare, lemma site.") + else: + lines.append("Setup is incomplete.") + if fixes: + lines += ["", "Next steps", *[f" {f}" for f in fixes]] + return "\n".join(lines), 0 if required_ok else 1 diff --git a/pipeline/lemma/draft.py b/pipeline/lemma/draft.py new file mode 100644 index 0000000..5a0ff6e --- /dev/null +++ b/pipeline/lemma/draft.py @@ -0,0 +1,159 @@ +"""Write a new construct from plain answers, submit the draft, explain the compiler's reply.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path + +from .config import Paths +from .lean import LeanMessage, lake_build, lean_check_file + +LEVELS = ["Individual", "Dyad", "Team", "Unit", "Organization"] +HORIZONS = ["Momentary", "Daily", "Weekly", "Monthly", "Annual", "Static"] +CATEGORIES = { + "AffectiveState": "An affective or affective-cognitive state", + "JobCharacteristic": "A characteristic of a job or work context", + "Disposition": "A relatively stable disposition", + "WorkBehavior": "A behavior or behavioral intention", + "Outcome": "A health or performance outcome", + "ResourceDynamic": "A change in resources over the horizon", +} + + +def parse_catalog(primitives_source: str) -> list[dict]: + """Read the vocabulary from ``Primitives.lean``, the one source of truth for parts.""" + enums = { + m.group(1): re.findall(r"\|\s*(\w+)", m.group(2)) + for m in re.finditer(r"inductive (\w+)\n((?:\s*\|\s*\w+\n)+)", primitives_source) + } + catalog = [] + for m in re.finditer(r"@\[primitive\] structure (\w+)((?: \(\w+ : \w+\))*) extends Primitive", primitives_source): + params = [{"name": n, "type": t, "values": enums[t]} for n, t in re.findall(r"\((\w+) : (\w+)\)", m.group(2))] + catalog.append({"prim": m.group(1), "params": params}) + return catalog + + +def all_parts(catalog: list[dict]) -> list[str]: + parts: list[str] = [] + for entry in catalog: + combos = [[]] + for param in entry["params"]: + combos = [[*c, v] for c in combos for v in param["values"]] + parts += [" ".join([entry["prim"], *c]) for c in combos] + return parts + + +def to_identifier(text: str) -> str: + """Turn ``work vitality`` into ``WorkVitality``, the form Lean expects for a construct name.""" + pieces = re.findall(r"[A-Za-z0-9]+", text) + name = "".join(p[0].upper() + p[1:] for p in pieces) + if not name or not name[0].isalpha(): + raise ValueError("A construct name needs at least one word starting with a letter.") + return name + + +def field_name(part: str) -> str: + pieces = part.split() + return pieces[0][0].lower() + pieces[0][1:] + "".join(pieces[1:]) + + +def lean_type(part: str) -> str: + pieces = part.split() + return " ".join([f"Lemma.{pieces[0]}", *[f".{a}" for a in pieces[1:]]]) + + +def docstring(definition: str, citation: str) -> str: + text = " ".join(f"{definition.strip().rstrip('.')} ({citation.strip() or 'citation to add'}).".split()) + return text.replace("-/", "- /").replace("/-", "/ -") + + +def render_lean( + name: str, + definition: str, + citation: str, + category: str, + level: str, + horizon: str, + parts: list[str], + generated: list[str], +) -> str: + """Keep in step with ``renderLean`` in ``site_assets/overlap.js``. A test compares the two.""" + imports = ["import Lemma", *[f"import Lemma.Generated.{m}" for m in generated]] + fields = [f" {field_name(p)} : {lean_type(p)}" for p in parts] + return "\n".join( + [ + *imports, + "", + f"namespace Lemma.Drafts.{name}", + "", + f"/-- {docstring(definition, citation)} -/", + f"@[construct] structure {name} extends {category} (level := .{level}) (horizon := .{horizon}) where", + *fields, + "", + f"end Lemma.Drafts.{name}", + "", + ] + ) + + +@dataclass +class Explained: + tone: str # "problem" | "attention" | "note" + headline: str + detail: str + raw: str + line: int + + +def explain(message: LeanMessage) -> Explained: + first = message.first_line + detail_lines = [ln.strip() for ln in message.data.splitlines()[1:]] + tone = {"error": "problem", "warning": "attention"}.get(message.severity, "note") + m = re.match(r"shares primitives? (.+?) with (\S+)", first) + if m: + kind = next((ln.split(":", 1)[1].split()[0] for ln in detail_lines if ln.startswith("overlap kind:")), "") + return Explained( + tone, + f"Shares {m.group(1)} with {m.group(2).rsplit('.', 1)[0]}", + f"Overlap kind {kind}. Record a decision with declare_overlap, naming the source of the distinction.", + message.data, + message.line, + ) + m = re.match(r"construct `(.+)` does not reduce to primitives", first) + if m: + return Explained( + tone, + f"{m.group(1)} uses something outside the vocabulary", + "Every field must be a registered part. Run lemma find to see the parts on offer.", + message.data, + message.line, + ) + if "requires a citation docstring" in first: + return Explained( + tone, "A citation is missing", "Add a definition with author, year, page.", message.data, message.line + ) + m = re.match(r"scope mismatch in `(.+?)`: (.*)", first) + if m: + return Explained(tone, f"The scope of {m.group(1)} does not line up", m.group(2), message.data, message.line) + if first.startswith("contradicts "): + return Explained(tone, "This claim disagrees with another theory", first, message.data, message.line) + if first.startswith("shape disagreement"): + return Explained(tone, "This claim differs in shape from another theory", first, message.data, message.line) + if " is routed through " in first: + return Explained(tone, "The claim connects through a registered rule", first, message.data, message.line) + return Explained(tone, "Compiler message", first, message.data, message.line) + + +def library_built(root: Path) -> bool: + return (root / ".lake" / "build" / "lib" / "Lemma.olean").exists() + + +def submit(paths: Paths, file: Path) -> tuple[bool, list[Explained]]: + if not library_built(paths.root): + print("Building the library for the first time. This takes a minute or two.") + built = lake_build(paths.root) + if not built.ok: + raise RuntimeError(built.stdout[-2000:] or built.stderr[-2000:]) + result = lean_check_file(paths.root, file.resolve()) + return result.ok, [explain(m) for m in result.messages] diff --git a/pipeline/lemma/explore.py b/pipeline/lemma/explore.py new file mode 100644 index 0000000..699066d --- /dev/null +++ b/pipeline/lemma/explore.py @@ -0,0 +1,312 @@ +"""Plain-language views of the compiled library. + +Everything here reads the checked-in reports, so these views work without +Lean. The overlap logic restates the key from ``Lemma/Meta/Overlap.lean``. +``tests/test_explore.py`` holds the restatement to the compiler's own output. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass +from pathlib import Path + +import yaml + +from .config import Paths + +PART_TEMPLATES = { + "Energy": ("En", "Energy"), + "Attention": ("At", "Attention to {}"), + "Identification": ("Id", "Identification with {}"), + "Demand": ("De", "{} demand"), + "Resource": ("Re", "{} resource"), + "Change": ("Ch", "Change in {} resource"), + "Affect": ("Af", "{} affect with {} activation"), + "Learning": ("Le", "Learning"), + "Efficacy": ("Ef", "Efficacy for {}"), + "Motivation": ("Mo", "{} motivation"), + "Skill": ("Sk", "Skill"), + "Symptom": ("Sy", "{} symptoms"), + "Performance": ("Pe", "{} performance"), + "Intention": ("In", "{} intention"), + "Trust": ("Tu", "Trust in {}"), + "Expectancy": ("Ex", "{} expectancy"), + "Behavior": ("Be", "{} behavior"), + "Trait": ("Tr", "{}"), +} + +KIND_MEANING = { + "identity": "The two constructs are built from exactly the same parts at the same scope.", + "subtype": "Every part of one construct also belongs to the other.", + "partial": "The two constructs share some parts while each keeps parts of its own.", + "none": "The two constructs share no part at the same scope.", +} + +PIPELINE_LABEL = "pipeline fixture" +CURATED_LABEL = "curated" + + +def tail(name: str) -> str: + return name.rsplit(".", 1)[-1] + + +def theory_name(name: str) -> str: + """``Lemma.Theories.JDR.JobDemands`` becomes ``JDR.JobDemands``.""" + return ".".join(name.split(".")[-2:]) + + +def words(identifier: str) -> str: + return re.sub(r"(?<=[a-z])(?=[A-Z])", " ", identifier) + + +def sentence_case(text: str) -> str: + return text[:1].upper() + text[1:] + + +def part_name(leaf: dict) -> str: + """``Attention Work``: the part as the compiler prints the part.""" + return " ".join([tail(leaf["prim"]), *[tail(a) for a in leaf["args"]]]) + + +def part_label(prim: str, args: list[str]) -> str: + _, template = PART_TEMPLATES.get(prim, (prim[:2], " ".join(["{}"] * max(len(args), 1)))) + if not args: + return template if "{}" not in template else prim + filled = template.format(*[words(a).lower() for a in args]) + return sentence_case(filled) + + +def part_key(leaf: dict) -> tuple: + """The overlap key from ``Lemma/Meta/Overlap.lean``: primitive, arguments, level, horizon.""" + return (leaf["prim"], tuple(leaf["args"]), leaf["level"], leaf["horizon"]) + + +def overlap_kind(keys_a: set, keys_b: set) -> str: + if not keys_a & keys_b: + return "none" + if keys_a == keys_b: + return "identity" + if keys_a < keys_b or keys_b < keys_a: + return "subtype" + return "partial" + + +def provenance(module: str) -> str: + return PIPELINE_LABEL if module.startswith("Lemma.Generated") else CURATED_LABEL + + +def _plain_scope(level: str, horizon: str) -> str: + return f"{level} / {horizon}" + + +class AmbiguousNameError(LookupError): + def __init__(self, query: str, options: list[str]): + super().__init__(query) + self.query = query + self.options = options + + +class UnknownNameError(LookupError): + def __init__(self, query: str, suggestions: list[str]): + super().__init__(query) + self.query = query + self.suggestions = suggestions + + +@dataclass +class Comparison: + a: dict + b: dict + kind: str + shared: list[str] + only_a: list[str] + only_b: list[str] + scope_shifts: list[str] + declaration: dict | None + claims: list[dict] + correlation: dict | None + + +class Library: + def __init__(self, paths: Paths): + self.paths = paths + self.report = _read_json(paths.reports / "library.json") + self.agenda = _read_json(paths.reports / "agenda.json") + self.distinctness = _read_json(paths.reports / "distinctness.json") + self.constructs = self.report["constructs"] + self.propositions = self.report["propositions"] + self.by_name = {c["name"]: c for c in self.constructs} + self.keys = {c["name"]: {part_key(leaf) for leaf in c["leaves"]} for c in self.constructs} + + def resolve(self, query: str) -> dict: + """Find a construct by ``Theory.Name`` or ``Name``. A lone curated match wins over fixture copies.""" + wanted = query.strip().lower().replace(" ", "") + exact = [c for c in self.constructs if theory_name(c["name"]).lower() == wanted or c["name"].lower() == wanted] + if len(exact) == 1: + return exact[0] + matches = [c for c in self.constructs if tail(c["name"]).lower() == wanted] + if len(matches) == 1: + return matches[0] + curated = [c for c in matches if provenance(c["module"]) == CURATED_LABEL] + if len(curated) == 1: + return curated[0] + if matches: + raise AmbiguousNameError(query, [theory_name(c["name"]) for c in matches]) + raise UnknownNameError(query, [theory_name(c["name"]) for c in self.find_constructs(query)[:5]]) + + def find_constructs(self, query: str) -> list[dict]: + terms = query.lower().split() + scored = [] + for c in self.constructs: + name = theory_name(c["name"]).lower() + parts = " ".join(part_name(leaf).lower() for leaf in c["leaves"]) + doc = c.get("doc", "").lower() + hay = f"{name} {parts} {doc}" + if not all(t in hay for t in terms): + continue + score = sum(4 if t in name else 2 if t in parts else 1 for t in terms) + scored.append((-score, name, c)) + return [c for _, _, c in sorted(scored, key=lambda row: row[:2])] + + def find_claims(self, query: str) -> list[dict]: + terms = query.lower().split() + out = [] + for p in self.propositions: + hay = " ".join([p["name"], p["antecedent"], p["consequent"], p.get("doc", ""), p.get("citation", "")]) + if all(t in hay.lower() for t in terms): + out.append(p) + return out + + def find_parts(self, query: str) -> list[dict]: + terms = query.lower().split() + return [ + p + for p in self.report["primitives"] + if all(t in f"{tail(p['name'])} {p.get('doc', '')}".lower() for t in terms) + ] + + def declaration(self, a: str, b: str) -> dict | None: + for d in self.report["overlap_declarations"]: + if {d["a"], d["b"]} == {a, b}: + return d + return None + + def claims_about(self, name: str) -> list[dict]: + return [p for p in self.propositions if name in (p["antecedent"], p["consequent"])] + + def overlaps_of(self, name: str) -> list[dict]: + return [o for o in self.report["overlaps"] if name in (o["a"], o["b"])] + + def compare(self, a: dict, b: dict) -> Comparison: + keys_a, keys_b = self.keys[a["name"]], self.keys[b["name"]] + labels = { + part_key(leaf): part_label(tail(leaf["prim"]), [tail(x) for x in leaf["args"]]) + for leaf in [*a["leaves"], *b["leaves"]] + } + prims_a = {(k[0], k[1]): k for k in keys_a} + shifts = sorted( + labels[k] + f": {_plain_scope(prims_a[(k[0], k[1])][2], prims_a[(k[0], k[1])][3])} against {k[2]} / {k[3]}" + for k in keys_b + if (k[0], k[1]) in prims_a and k not in keys_a + ) + correlation = None + wanted = {tail(a["name"]), tail(b["name"])} + for row in self.distinctness.get("rows", []): + if {row["a"], row["b"]} == wanted: + correlation = row + return Comparison( + a=a, + b=b, + kind=overlap_kind(keys_a, keys_b), + shared=sorted(labels[k] for k in keys_a & keys_b), + only_a=sorted(labels[k] for k in keys_a - keys_b), + only_b=sorted(labels[k] for k in keys_b - keys_a), + scope_shifts=shifts, + declaration=self.declaration(a["name"], b["name"]), + claims=[p for p in self.propositions if {p["antecedent"], p["consequent"]} == {a["name"], b["name"]}], + correlation=correlation, + ) + + +def _read_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def clean_doc(doc: str) -> str: + return " ".join((doc or "").split()) + + +def load_curation(paths: Paths) -> dict: + with (paths.config / "curation.yaml").open(encoding="utf-8") as fh: + return yaml.safe_load(fh) + + +def fill_counts(text: str, report: dict) -> str: + """Curated copy states counts through placeholders, so every count stays generated.""" + return text.format(**report["summary"], papers_pipeline_total=report["formalization"]["papers"]) + + +def describe_construct(lib: Library, c: dict) -> str: + lines = [ + theory_name(c["name"]), + f" Source of entry {provenance(c['module'])}", + f" Scope {_plain_scope(c['level'], c['horizon'])}", + "", + " Definition", + f" {clean_doc(c.get('doc', ''))}", + "", + " Built from", + ] + for leaf in c["leaves"]: + lines.append(f" {part_label(tail(leaf['prim']), [tail(a) for a in leaf['args']])}") + overlaps = lib.overlaps_of(c["name"]) + if overlaps: + lines += ["", f" Shares parts with {len(overlaps)} other constructs"] + for o in overlaps[:12]: + other = o["b"] if o["a"] == c["name"] else o["a"] + declared = "declared " + o["declared"]["kind"] if o.get("declared") else "undeclared" + lines.append(f" {theory_name(other):38s} {o['kind']:9s} {declared}") + if len(overlaps) > 12: + lines.append(f" plus {len(overlaps) - 12} more") + claims = lib.claims_about(c["name"]) + if claims: + lines += ["", f" Appears in {len(claims)} claims"] + for p in claims[:12]: + lines.append(f" {format_claim(p)}") + if len(claims) > 12: + lines.append(f" plus {len(claims) - 12} more") + return "\n".join(lines) + + +def format_claim(p: dict) -> str: + return ( + f"{tail(p['antecedent'])} → {tail(p['consequent'])}: {p['direction']}, " + f"{p['evidence']} evidence, stated in {p['theory']}" + ) + + +def describe_comparison(cmp: Comparison) -> str: + a, b = theory_name(cmp.a["name"]), theory_name(cmp.b["name"]) + lines = [f"{a} compared with {b}", f" Result {cmp.kind}. {KIND_MEANING[cmp.kind]}"] + for title, items in ( + ("Shared parts", cmp.shared), + (f"Only in {a}", cmp.only_a), + (f"Only in {b}", cmp.only_b), + ("Same part at a different scope", cmp.scope_shifts), + ): + if items: + lines += ["", f" {title}", *[f" {i}" for i in items]] + if cmp.declaration: + lines += ["", " Recorded decision", f" {cmp.declaration['kind']}: {clean_doc(cmp.declaration['reason'])}"] + if cmp.claims: + lines += ["", " Claims linking the pair", *[f" {format_claim(p)}" for p in cmp.claims]] + if cmp.correlation: + row = cmp.correlation + lines += [ + "", + f" Correlation on file {row['rho']}", + f" Status {row['status']}. Placeholder and recalled values await a check against the source.", + ] + return "\n".join(lines) diff --git a/pipeline/lemma/site.py b/pipeline/lemma/site.py new file mode 100644 index 0000000..6320886 --- /dev/null +++ b/pipeline/lemma/site.py @@ -0,0 +1,222 @@ +"""``lemma site``: build the Explorer, one self-contained page generated from the reports.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from .check import generated_modules +from .config import Paths +from .draft import CATEGORIES, HORIZONS, LEVELS, parse_catalog +from .explore import ( + PART_TEMPLATES, + Library, + clean_doc, + fill_counts, + load_curation, + part_label, + part_name, + provenance, + tail, + theory_name, +) + +ASSETS = Path(__file__).parent / "site_assets" +REPOSITORY = "https://github.com/sumervaid/lemma" + + +def _source_url(module: str) -> str: + return f"{REPOSITORY}/blob/main/{module.replace('.', '/')}.lean" + + +def _boundary(b: dict) -> str: + if b.get("kind") == "moderator": + return f"{b['effect']} by {tail(b['construct'])}" + if b.get("kind") == "scope": + return b.get("description", "") + return "" + + +def build_data(paths: Paths) -> dict: + lib = Library(paths) + report = lib.report + curation = load_curation(paths) + catalog = parse_catalog((paths.root / "Lemma" / "Library" / "Primitives.lean").read_text(encoding="utf-8")) + docs = {tail(p["name"]): clean_doc(p.get("doc", "")) for p in report["primitives"]} + + uses: dict[str, int] = {} + constructs = [] + for c in lib.constructs: + parts = [] + seen = set() + for leaf in c["leaves"]: + name = part_name(leaf) + key = f"{name}|{leaf['level']}|{leaf['horizon']}" + if key in seen: + continue + seen.add(key) + prim = tail(leaf["prim"]) + args = [tail(a) for a in leaf["args"]] + parts.append( + { + "key": key, + "part": name, + "prim": prim, + "label": part_label(prim, args), + "sym": PART_TEMPLATES[prim][0], + } + ) + for prim in {p["prim"] for p in parts}: + uses[prim] = uses.get(prim, 0) + 1 + constructs.append( + { + "id": theory_name(c["name"]), + "short": tail(c["name"]), + "theory": c["theory"], + "origin": provenance(c["module"]), + "level": c["level"], + "horizon": c["horizon"], + "doc": clean_doc(c.get("doc", "")), + "source": _source_url(c["module"]), + "parts": parts, + "components": [theory_name(x) for x in c.get("components", [])], + } + ) + + propositions = [ + { + "id": theory_name(p["name"]), + "a": theory_name(p["antecedent"]), + "b": theory_name(p["consequent"]), + "direction": p["direction"], + "scope": f"{p['level']} / {p['horizon']}", + "evidence": p["evidence"], + "theory": p["theory"], + "origin": provenance(p["module"]), + "citation": p.get("citation", ""), + "doc": clean_doc(p.get("doc", "")), + "boundary": _boundary(p.get("boundary", {})), + } + for p in lib.propositions + ] + overlaps = [ + { + "a": theory_name(o["a"]), + "b": theory_name(o["b"]), + "kind": o["kind"], + "declared": ( + {"kind": o["declared"]["kind"], "reason": clean_doc(o["declared"]["reason"])} + if o.get("declared") + else None + ), + } + for o in report["overlaps"] + ] + declarations = [ + {"a": theory_name(d["a"]), "b": theory_name(d["b"]), "kind": d["kind"], "reason": clean_doc(d["reason"])} + for d in report["overlap_declarations"] + ] + agenda = [ + { + "kind": i["kind"], + "a": i["antecedent"], + "b": i["consequent"], + "direction": i["direction"], + "scope": f"{i['level']} / {i['horizon']}", + "theories": i["theories"], + "evidence": i["evidence"], + "score": round(i["score"], 3), + "why": i["rationale"], + } + for i in lib.agenda["items"] + ] + + def pair(row: dict) -> dict: + return {**row, "antecedent": theory_name(row["antecedent"]), "consequent": theory_name(row["consequent"])} + + implied_conflicts = [ + { + "a": theory_name(i["antecedent"]), + "b": theory_name(i["consequent"]), + "direction": i["direction"], + "registered": theory_name(i["registered"]) if i.get("registered") else "", + "theories": i["theories"], + "scope": f"{i['level']} / {i['horizon']}", + } + for i in report["implied"] + if i["status"] == "contradicted" + ] + failures = [ + { + "paper": f["paper_id"], + "status": f["status"], + "reason": clean_doc(f.get("reason", "")), + "notes": [clean_doc(x) for x in f.get("ambiguities", [])], + "errors": [clean_doc(x if isinstance(x, str) else x.get("message", "")) for x in f.get("errors", [])], + } + for f in report["formalization"]["failures"] + ] + catalog_out = [ + { + **entry, + "sym": PART_TEMPLATES[entry["prim"]][0], + "doc": docs.get(entry["prim"], ""), + "uses": uses.get(entry["prim"], 0), + } + for entry in catalog + ] + findings = [ + {**f, "title": fill_counts(f["title"], report), "body": fill_counts(f["body"], report)} + for f in curation["findings"] + ] + return { + "generatedAt": report["generated_at"], + "repository": REPOSITORY, + "summary": report["summary"], + "status": fill_counts(curation["status"], report), + "findings": findings, + "collections": curation["collections"], + "catalog": catalog_out, + "constructs": constructs, + "propositions": propositions, + "overlaps": overlaps, + "declarations": declarations, + "contradictions": [pair(x) for x in report["contradictions"]], + "conditional": [pair(x) for x in report["conditional_disagreements"]], + "shape": [pair(x) for x in report["shape_disagreements"]], + "convergences": [pair(x) for x in report["convergences"]], + "impliedConflicts": implied_conflicts, + "failures": failures, + "agenda": agenda, + "correlations": lib.distinctness.get("rows", []), + "sources": report["sources"], + "levels": LEVELS, + "horizons": HORIZONS, + "categories": CATEGORIES, + "generated": generated_modules(paths), + } + + +def _asset(name: str) -> str: + return (ASSETS / name).read_text(encoding="utf-8") + + +def render_page(data: dict, fragment: bool = False) -> str: + """``fragment`` omits the document shell, for hosts which supply their own.""" + payload = json.dumps(data, ensure_ascii=False, separators=(",", ":")).replace("<", "\\u003c") + head = _asset("head.html").replace("/*STYLES*/", _asset("styles.css")) + body = ( + _asset("body.html") + .replace("/*DATA*/", payload) + .replace("/*OVERLAP*/", _asset("overlap.js")) + .replace("/*APP*/", _asset("app.js")) + ) + if fragment: + return f"{head}\n{body}\n" + return f'\n\n\n\n{head}\n\n\n{body}\n\n\n' + + +def build_site(paths: Paths, out: Path, fragment: bool = False) -> Path: + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(render_page(build_data(paths), fragment=fragment), encoding="utf-8") + return out diff --git a/pipeline/lemma/site_assets/app.js b/pipeline/lemma/site_assets/app.js new file mode 100644 index 0000000..28f73b0 --- /dev/null +++ b/pipeline/lemma/site_assets/app.js @@ -0,0 +1,440 @@ +(function () { + "use strict"; + var D = JSON.parse(document.getElementById("lemma-data").textContent); + var Core = window.LemmaCore; + var view = document.getElementById("view"); + var byId = {}; + D.constructs.forEach(function (c) { byId[c.id] = c; }); + var state = { + q: "", theory: "", origin: "", part: "", claimQ: "", evidence: "", direction: "", agendaKind: "", + a: "Burnout.Exhaustion", b: "Engagement.Vigor", + draft: { + name: "Work Vitality", definition: "A felt sense of energy and focus across the working week.", + citation: "Example draft, replace with author, year, page", category: "AffectiveState", + level: "Individual", horizon: "Weekly", parts: ["Energy", "Attention Work"], picker: "Learning" + } + }; + var NAV = [["start", "Overview"], ["constructs", "Constructs"], ["compare", "Compare"], ["claims", "Claims"], + ["disagreements", "Disagreements"], ["agenda", "Agenda"], ["draft", "Draft a construct"], ["guide", "Guide"]]; + var KIND = { + identity: "Identical definitions. Both constructs use exactly these parts at this scope.", + subtype: "Nested definitions. Every part of one construct also belongs to the other.", + partial: "Partial overlap. The constructs share some parts while each keeps parts of its own.", + none: "Separate definitions. The constructs share no part at the same scope." + }; + + function esc(v) { + return String(v == null ? "" : v).replace(/[&<>"']/g, function (ch) { + return { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[ch]; + }); + } + function short(id) { return String(id).split(".").pop(); } + function hashId(id) { return String(id).replace(/\./g, "-"); } + function unhash(s) { + var found = null; + D.constructs.forEach(function (c) { if (hashId(c.id) === s) found = c; }); + return found; + } + function originPill(o) { + return o === "curated" ? 'curated' : 'pipeline fixture'; + } + function chip(p, cls) { return '' + esc(p.sym) + "" + esc(p.label) + ""; } + function cLink(id) { + return byId[id] ? '' + esc(id) + "" : esc(id); + } + function csvButton(id) { return ''; } + function saveCsv(name, rows) { + var text = rows.map(function (r) { + return r.map(function (v) { + var s = String(v == null ? "" : v); + return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; + }).join(","); + }).join("\n"); + var a = document.createElement("a"); + a.href = URL.createObjectURL(new Blob([text], { type: "text/csv" })); + a.download = name; + document.body.appendChild(a); a.click(); a.remove(); + } + function options(list, sel, blank) { + return (blank ? '" : "") + list.map(function (o) { + return '"; + }).join(""); + } + function uniq(list) { return Array.from(new Set(list)).sort(); } + function constructOptions(sel) { + var groups = {}; + D.constructs.forEach(function (c) { (groups[c.theory] = groups[c.theory] || []).push(c); }); + return Object.keys(groups).sort().map(function (t) { + return '' + groups[t].map(function (c) { + return '"; + }).join("") + ""; + }).join(""); + } + function go(hash) { + if (location.hash === "#" + hash) route(); else location.hash = hash; + } + function bindGo() { + view.querySelectorAll("[data-go]").forEach(function (el) { + el.addEventListener("click", function () { go(el.getAttribute("data-go")); }); + }); + view.querySelectorAll("[data-compare]").forEach(function (el) { + el.addEventListener("click", function () { + var pair = el.getAttribute("data-compare").split("|"); + state.a = pair[0]; state.b = pair[1]; go("compare"); + }); + }); + } + + /* Overview */ + function start() { + var s = D.summary; + var max = Math.max.apply(null, D.catalog.map(function (p) { return p.uses; })); + var tiles = D.catalog.map(function (p) { + return '"; + }).join(""); + var findings = D.findings.map(function (f) { + var action = f.compare + ? '' + : ''; + return '

' + esc(f.title) + "

" + esc(f.body) + '

' + esc(f.caution) + "

" + action + "
"; + }).join(""); + var collections = D.collections.map(function (col) { + return '

' + esc(col.title) + "

" + esc(col.blurb) + '
' + + col.constructs.map(function (id) { return '' + esc(id) + ""; }).join("") + "
"; + }).join(""); + view.innerHTML = + '

Organizational theory, checked like code.

' + + "

Lemma writes every construct from a small vocabulary of basic parts at a stated level of analysis with a stated time horizon. A compiler then reports shared parts, undeclared scopes, disagreements among theories, plus claims the library implies. Everything below runs in this page, with nothing to install.

" + + '
' + [[s.constructs, "constructs"], [s.propositions, "claims"], [s.theories, "theories"], [s.papers_total, "source papers"], [s.primitives, "parts"]].map(function (x) { + return "
" + x[0] + "" + x[1] + "
"; + }).join("") + "
" + + '
' + esc(D.status) + "
" + + '

The table of parts

Each number counts the constructs using a part. Select a tile to list those constructs.
' + tiles + "
" + + '

What the compiler reports

' + findings + "
" + + '

Good places to start

' + collections + "
"; + view.querySelectorAll("[data-part]").forEach(function (el) { + el.addEventListener("click", function () { + state.part = el.getAttribute("data-part"); state.q = ""; state.theory = ""; state.origin = ""; go("constructs"); + }); + }); + bindGo(); + } + + /* Constructs */ + function matchesConstruct(c) { + var q = state.q.toLowerCase().trim(); + if (state.theory && c.theory !== state.theory) return false; + if (state.origin && c.origin !== state.origin) return false; + if (state.part && !c.parts.some(function (p) { return p.prim === state.part; })) return false; + if (!q) return true; + var hay = (c.id + " " + c.doc + " " + c.parts.map(function (p) { return p.label; }).join(" ")).toLowerCase(); + return q.split(/\s+/).every(function (t) { return hay.indexOf(t) >= 0; }); + } + function constructRows() { + var rows = D.constructs.filter(matchesConstruct); + document.getElementById("count").textContent = rows.length + " of " + D.constructs.length; + document.getElementById("rows").innerHTML = rows.length ? rows.map(function (c) { + return '' + esc(c.short) + "" + esc(c.theory) + "" + esc(c.level + " / " + c.horizon) + '
' + c.parts.map(function (p) { return chip(p); }).join("") + "
" + originPill(c.origin) + ""; + }).join("") : 'Nothing matches. Clear a filter or try one broader word.'; + document.querySelectorAll("tr.row").forEach(function (tr) { + tr.addEventListener("click", function (e) { + if (e.target.tagName !== "A") go("c-" + hashId(tr.getAttribute("data-id"))); + }); + }); + } + function constructs() { + view.innerHTML = + '

Constructs

' + + '
' + + '' + + '" + + '" + + '" + + csvButton("csv") + "
" + + '
ConstructTheoryScopeBuilt fromEntry
'; + [["q", "q", "input"], ["theory", "theory", "change"], ["part", "part", "change"], ["origin", "origin", "change"]].forEach(function (x) { + document.getElementById(x[0]).addEventListener(x[2], function (e) { state[x[1]] = e.target.value; constructRows(); }); + }); + document.getElementById("csv").addEventListener("click", function () { + saveCsv("lemma-constructs.csv", [["construct", "theory", "level", "horizon", "parts", "source_of_entry", "definition"]].concat(D.constructs.filter(matchesConstruct).map(function (c) { + return [c.id, c.theory, c.level, c.horizon, c.parts.map(function (p) { return p.label; }).join("; "), c.origin, c.doc]; + }))); + }); + constructRows(); + } + function constructDetail(c) { + var overlaps = D.overlaps.filter(function (o) { return o.a === c.id || o.b === c.id; }); + var claims = D.propositions.filter(function (p) { return p.a === c.id || p.b === c.id; }); + view.innerHTML = + '

' + esc(c.short) + '

' + + '
' + esc(c.theory) + '' + esc(c.level + " / " + c.horizon) + "" + originPill(c.origin) + 'Read the source file
' + + '

' + esc(c.doc) + "

" + + '
Built from
' + c.parts.map(function (p) { return chip(p); }).join("") + "
" + + "

Shares parts with " + overlaps.length + ' constructs

' + (overlaps.length ? '
' + overlaps.map(function (o) { + var other = o.a === c.id ? o.b : o.a; + return "'; + }).join("") + "
ConstructOverlapRecorded decision
" + cLink(other) + '' + esc(o.kind) + "" + (o.declared ? esc(o.declared.kind + ". " + o.declared.reason) : 'awaiting a decision') + '
" : '

This construct shares no part with another at the same scope.

') + "
" + + "

Appears in " + claims.length + " claims

" + (claims.length ? claimTable(claims) : '

No claim in the library uses this construct.

') + "
"; + bindGo(); + } + + /* Compare */ + function comparison() { + var a = byId[state.a], b = byId[state.b]; + if (!a || !b) return '

Pick two constructs.

'; + var ka = a.parts.map(function (p) { return p.key; }), kb = b.parts.map(function (p) { return p.key; }); + var kind = Core.overlapKind(ka, kb); + var shared = a.parts.filter(function (p) { return kb.indexOf(p.key) >= 0; }); + var onlyA = a.parts.filter(function (p) { return kb.indexOf(p.key) < 0; }); + var onlyB = b.parts.filter(function (p) { return ka.indexOf(p.key) < 0; }); + var shifts = onlyB.filter(function (p) { return onlyA.some(function (q) { return q.part === p.part; }); }); + var decl = D.declarations.filter(function (d) { return (d.a === a.id && d.b === b.id) || (d.a === b.id && d.b === a.id); })[0]; + var claims = D.propositions.filter(function (p) { return (p.a === a.id && p.b === b.id) || (p.a === b.id && p.b === a.id); }); + var corr = D.correlations.filter(function (r) { return (r.a === a.short && r.b === b.short) || (r.a === b.short && r.b === a.short); })[0]; + function col(title, list, cls) { + return "
" + esc(title) + '
' + (list.length ? list.map(function (p) { return chip(p, cls); }).join("") : 'None') + "
"; + } + return '
' + esc(KIND[kind].split(". ")[0]) + '' + esc(KIND[kind].split(". ").slice(1).join(". ")) + "
" + + '
' + col("Shared", shared, "shared") + col("Only in " + a.id, onlyA) + col("Only in " + b.id, onlyB) + "
" + + (shifts.length ? '

The same part appears at a different scope: ' + esc(shifts.map(function (p) { return p.label; }).join(", ")) + ". A temporal or aggregation rule could connect them.

" : "") + + '
' + esc(a.id) + '

' + esc(a.doc) + "

" + esc(b.id) + '

' + esc(b.doc) + "

" + + (decl ? '
Recorded decision

' + esc(decl.kind) + " " + esc(decl.reason) + "

" : "") + + (corr ? '
Correlation on file ' + esc(corr.rho) + ". Status " + esc(corr.status) + ". This value awaits a check against " + esc(corr.source || "a source") + ".
" : "") + + (claims.length ? '
Claims linking the pair
' + claimTable(claims) + "
" : "") + "
"; + } + function compare() { + view.innerHTML = '

Compare two constructs

The result comes from the parts each definition uses, the same rule the compiler applies. Empirical distinctness is a separate question.

' + + '
" + + '

Pairs worth seeing

' + D.findings.filter(function (f) { return f.compare; }).map(function (f) { + return '"; + }).join("") + '
'; + function draw() { document.getElementById("cmp").innerHTML = comparison(); } + document.getElementById("ca").addEventListener("change", function (e) { state.a = e.target.value; draw(); }); + document.getElementById("cb").addEventListener("change", function (e) { state.b = e.target.value; draw(); }); + view.querySelectorAll("[data-compare]").forEach(function (el) { + el.addEventListener("click", function () { + var pair = el.getAttribute("data-compare").split("|"); + state.a = pair[0]; state.b = pair[1]; + document.getElementById("ca").value = state.a; document.getElementById("cb").value = state.b; draw(); + }); + }); + draw(); + } + + /* Claims */ + function claimTable(list) { + return '
' + list.map(function (p) { + return ""; + }).join("") + "
ClaimDirectionEvidenceStated inCitation
" + cLink(p.a) + " → " + cLink(p.b) + (p.boundary ? '
' + esc(p.boundary) + "" : "") + '
' + esc(p.direction) + "" + esc(p.evidence) + "" + esc(p.theory) + (p.origin === "curated" ? "" : '
pipeline fixture') + "
" + esc(p.citation) + "
"; + } + function matchesClaim(p) { + if (state.evidence && p.evidence !== state.evidence) return false; + if (state.direction && p.direction !== state.direction) return false; + var q = state.claimQ.toLowerCase().trim(); + if (!q) return true; + var hay = (p.a + " " + p.b + " " + p.doc + " " + p.citation + " " + p.theory).toLowerCase(); + return q.split(/\s+/).every(function (t) { return hay.indexOf(t) >= 0; }); + } + function claims() { + view.innerHTML = '

Claims

' + + '' + + '" + + '" + + csvButton("csv") + '
'; + function draw() { + var rows = D.propositions.filter(matchesClaim); + document.getElementById("count").textContent = rows.length + " of " + D.propositions.length; + document.getElementById("tbl").innerHTML = rows.length ? claimTable(rows) : '

Nothing matches. Clear a filter or try one broader word.

'; + } + document.getElementById("cq").addEventListener("input", function (e) { state.claimQ = e.target.value; draw(); }); + document.getElementById("ev").addEventListener("change", function (e) { state.evidence = e.target.value; draw(); }); + document.getElementById("dir").addEventListener("change", function (e) { state.direction = e.target.value; draw(); }); + document.getElementById("csv").addEventListener("click", function () { + saveCsv("lemma-claims.csv", [["antecedent", "consequent", "direction", "scope", "evidence", "boundary", "theory", "source_of_entry", "citation"]].concat(D.propositions.filter(matchesClaim).map(function (p) { + return [p.a, p.b, p.direction, p.scope, p.evidence, p.boundary, p.theory, p.origin, p.citation]; + }))); + }); + draw(); + } + + /* Disagreements */ + function simpleTable(head, rows) { + return '
' + head.map(function (h) { return ""; }).join("") + "" + rows.join("") + "
" + esc(h) + "
"; + } + function disagreements() { + var dir = function (d) { return '' + esc(d) + ""; }; + var pairRow = function (x) { return cLink(x.antecedent) + " → " + cLink(x.consequent); }; + view.innerHTML = + '

Where theories part ways

The compiler compares claims with one pair of constructs, one scope, one boundary condition. Each result rests on the author\'s readings of the sources.

' + + "

Direct contradictions

" + simpleTable(["Pair", "First theory", "Second theory", "Scope"], D.contradictions.map(function (x) { return "" + pairRow(x) + "" + esc(x.theoryA) + " " + dir(x.directionA) + "" + esc(x.theoryB) + " " + dir(x.directionB) + "" + esc(x.level + " / " + x.horizon) + ""; })) + "
" + + '

Implied against direct

Chaining two claims implies a sign which a direct claim in the library contradicts.

' + simpleTable(["Pair", "Implied", "Direct claim", "Theories"], D.impliedConflicts.map(function (x) { return "" + cLink(x.a) + " → " + cLink(x.b) + "" + dir(x.direction) + "" + esc(x.registered) + "" + esc(x.theories.join(", ")) + ""; })) + "
" + + '

Disagreement under a condition

Opposing directions under different boundary conditions.

' + simpleTable(["Pair", "First theory", "Second theory"], D.conditional.map(function (x) { return "" + pairRow(x) + "" + esc(x.theoryA) + " " + dir(x.directionA) + "" + esc(x.theoryB) + " " + dir(x.directionB) + "
" + esc(x.boundaryB) + ""; })) + "
" + + '

Disagreement on shape

One theory states a straight relation while another states a curve.

' + simpleTable(["Pair", "First theory", "Second theory"], D.shape.map(function (x) { return "" + pairRow(x) + "" + esc(x.theoryA) + " " + dir(x.directionA) + "" + esc(x.theoryB) + " " + dir(x.directionB) + ""; })) + "
" + + '

Agreement across theories

The same claim stated in two or more theories.

' + simpleTable(["Pair", "Direction", "Theories"], D.convergences.map(function (x) { return "" + pairRow(x) + "" + dir(x.direction) + "" + esc(x.theories.join(", ")) + ""; })) + "
" + + '

Papers the pipeline refused

Hand-written fixtures produced these outcomes in order to exercise the pipeline. No model ran.
    ' + D.failures.map(function (f) { + var notes = f.reason ? [f.reason] : f.notes.slice(0, 1); + return '
  • ' + esc(f.status) + " " + esc(f.paper) + "
    " + esc(notes.join(" ")) + "
  • "; + }).join("") + "
"; + } + + /* Agenda */ + function agenda() { + var w = "Score = 0.40 evidence weakness + 0.25 structural load + 0.25 disagreement + 0.10 implied."; + view.innerHTML = '

The verification agenda

A ranking of where a new study would teach the library the most. ' + esc(w) + " Implied rows name pairs with no direct claim in the library. Many may already have tests in the wider literature.

" + + '
" + csvButton("csv") + '
'; + function rows() { return D.agenda.filter(function (i) { return !state.agendaKind || i.kind === state.agendaKind; }); } + function draw() { + document.getElementById("tbl").innerHTML = simpleTable(["Rank", "Score", "Pair", "Kind", "Direction", "Why"], rows().slice(0, 60).map(function (i, n) { + return '' + (n + 1) + '' + i.score.toFixed(3) + "" + cLink(i.a) + " → " + cLink(i.b) + '' + esc(i.kind) + '' + esc(i.direction) + "
Reasons" + i.why.map(function (y) { return "
" + esc(y) + "
"; }).join("") + "
"; + })) + (rows().length > 60 ? '

Showing the top 60 of ' + rows().length + ". The CSV holds every row.

" : ""); + } + document.getElementById("ak").addEventListener("change", function (e) { state.agendaKind = e.target.value; draw(); }); + document.getElementById("csv").addEventListener("click", function () { + saveCsv("lemma-agenda.csv", [["rank", "score", "antecedent", "consequent", "kind", "direction", "scope", "evidence", "theories"]].concat(rows().map(function (i, n) { + return [n + 1, i.score, i.a, i.b, i.kind, i.direction, i.scope, i.evidence, i.theories.join("; ")]; + }))); + }); + draw(); + } + + /* Draft */ + function partChoices() { + var out = []; + D.catalog.forEach(function (entry) { + var combos = [[]]; + entry.params.forEach(function (param) { + var next = []; + combos.forEach(function (c) { param.values.forEach(function (v) { next.push(c.concat([v])); }); }); + combos = next; + }); + combos.forEach(function (c) { out.push({ part: [entry.prim].concat(c).join(" "), prim: entry.prim, sym: entry.sym, args: c }); }); + }); + return out; + } + var CHOICES = partChoices(); + var LABELS = {}; + D.constructs.forEach(function (c) { c.parts.forEach(function (p) { LABELS[p.part] = p.label; }); }); + function labelOf(part) { return LABELS[part] || part.replace(/([a-z])([A-Z])/g, "$1 $2"); } + function draftResults() { + var d = state.draft; + var name = Core.toIdentifier(d.name); + var keys = d.parts.map(function (p) { return p + "|" + d.level + "|" + d.horizon; }); + var hits = D.constructs.map(function (c) { + return { c: c, kind: Core.overlapKind(keys, c.parts.map(function (p) { return p.key; })) }; + }).filter(function (h) { return h.kind !== "none"; }); + var order = { identity: 0, subtype: 1, partial: 2 }; + hits.sort(function (x, y) { return order[x.kind] - order[y.kind] || x.c.id.localeCompare(y.c.id); }); + var counts = { identity: 0, subtype: 0, partial: 0 }; + hits.forEach(function (h) { counts[h.kind] += 1; }); + var verdict = !d.parts.length ? "Add at least one part." + : !/^[A-Za-z]/.test(name) ? "A name needs a word starting with a letter." + : counts.identity ? counts.identity + " existing constructs have exactly this definition." + : hits.length ? "This draft overlaps " + hits.length + " existing constructs." + : "This draft overlaps nothing in the library at this scope."; + var valid = d.parts.length && /^[A-Za-z]/.test(name); + var lean = valid ? Core.renderLean({ name: name, definition: d.definition, citation: d.citation, category: d.category, level: d.level, horizon: d.horizon, parts: d.parts, generated: D.generated }) : ""; + document.getElementById("draft-out").innerHTML = + '
' + esc(verdict) + '' + counts.identity + " identical, " + counts.subtype + " nested, " + counts.partial + " partial. Each overlap asks for a recorded decision with a stated reason.
" + + (hits.length ? '
' + hits.slice(0, 40).map(function (h) { + return ""; + }).join("") + "
ConstructOverlapEntry
" + cLink(h.c.id) + '' + esc(h.kind) + "" + originPill(h.c.origin) + "
" : "") + + (valid ? '
Ready to compile
' + esc(lean) + "
" : "") + + '

This page applies the overlap rule alone. The compiler runs all four checks. Save the file as drafts/' + esc(valid ? name : "MyIdea") + '.lean, then run lemma try on the file, or open a discussion to propose the construct.

'; + var copy = document.getElementById("copy"); + if (copy) copy.addEventListener("click", function () { + var done = function () { copy.textContent = "Copied"; }; + var fallback = function () { + var r = document.createRange(); r.selectNodeContents(document.getElementById("lean")); + var s = getSelection(); s.removeAllRanges(); s.addRange(r); copy.textContent = "Selected, press copy"; + }; + if (navigator.clipboard) navigator.clipboard.writeText(lean).then(done, fallback); else fallback(); + }); + } + function draftChips() { + document.getElementById("draft-parts").innerHTML = state.draft.parts.map(function (p, i) { + var entry = CHOICES.filter(function (c) { return c.part === p; })[0]; + return '' + esc(entry ? entry.sym : "?") + "" + esc(labelOf(p)) + ''; + }).join("") || 'No parts yet.'; + document.querySelectorAll("[data-rm]").forEach(function (b) { + b.addEventListener("click", function () { + state.draft.parts.splice(Number(b.getAttribute("data-rm")), 1); + draftChips(); draftResults(); + }); + }); + } + function draft() { + var d = state.draft; + var groups = {}; + CHOICES.forEach(function (c) { (groups[c.prim] = groups[c.prim] || []).push(c); }); + var pick = Object.keys(groups).map(function (prim) { + return '' + groups[prim].map(function (c) { + return '"; + }).join("") + ""; + }).join(""); + var cats = Object.keys(D.categories).map(function (k) { + return '"; + }).join(""); + view.innerHTML = '

Draft a construct

Describe an idea in plain terms. The library answers at once with every construct already built from the same parts. The example below is a sample to edit.

' + + '
' + + '' + + '" + + '' + + '" + + '
" + + '
Parts
' + + '
' + + '
'; + [["d-name", "name"], ["d-def", "definition"], ["d-cit", "citation"]].forEach(function (x) { + document.getElementById(x[0]).addEventListener("input", function (e) { d[x[1]] = e.target.value; draftResults(); }); + }); + [["d-cat", "category"], ["d-lev", "level"], ["d-hor", "horizon"]].forEach(function (x) { + document.getElementById(x[0]).addEventListener("change", function (e) { d[x[1]] = e.target.value; draftResults(); }); + }); + document.getElementById("d-pick").addEventListener("change", function (e) { d.picker = e.target.value; }); + document.getElementById("d-add").addEventListener("click", function () { + var value = document.getElementById("d-pick").value; + if (d.parts.indexOf(value) < 0) d.parts.push(value); + draftChips(); draftResults(); + }); + document.getElementById("draft-form").addEventListener("submit", function (e) { e.preventDefault(); }); + draftChips(); draftResults(); + } + + /* Guide */ + function guide() { + var terms = [ + ["Part", "A basic quantity such as energy or attention. The library calls these primitives. Parts carry no sign, so a construct states in the definition whether the construct reads the high pole or the low pole."], + ["Construct", "A named concept written as a set of parts at one level of analysis with one time horizon."], + ["Scope", "The pairing of a level of analysis with a time horizon, such as Individual / Weekly."], + ["Claim", "A typed statement linking two constructs, with a direction, a scope, an evidence kind, a citation. The library calls these propositions."], + ["Overlap", "Two constructs sharing at least one part at the same scope. Identical means the same parts. Nested means one set sits inside the other. Partial means each keeps parts of its own."], + ["Recorded decision", "A statement by a scholar on an overlap, marking the pair distinct, an alias, or a subtype, with a reason."], + ["Implied pair", "A relation produced by chaining two claims. Untested in the reports means the library holds no direct claim on the pair. The wider literature may hold tests."], + ["Curated entry", "A definition or claim the author wrote from the cited source. Fidelity to the source is itself a verification task."], + ["Pipeline fixture", "An entry from a hand-written file standing in for model output. No model produced any entry in this release."] + ]; + view.innerHTML = '

Guide

Three ways in, with no prior knowledge of Lean.

' + + '

Browse here

Every page on this site runs in the browser. Start with the table of parts, then compare two constructs.

' + + '

Use a cloud workspace

A GitHub account opens a ready workspace with the compiler in place. Open a Codespace, then run lemma new in the terminal.

' + + '

Install on a laptop

On macOS or Linux, paste one line into Terminal. Windows users can take the cloud workspace.

curl -fsSL https://raw.githubusercontent.com/sumervaid/lemma/main/install.sh | bash
' + + '

Terms

' + terms.map(function (t) { return ""; }).join("") + "
" + esc(t[0]) + "" + esc(t[1]) + "
" + + '

What this release leaves open

  • No model has run. Precision is unmeasured.
  • Correlations on file are placeholder or recalled values, each labelled.
  • Four source readings await a check, listed in section J of the technical appendix.
  • Composition stops at chains of two claims, and an implied sign describes one path.
' + + "

Sources

" + D.sources.length + ' curated sources
    ' + D.sources.map(function (s) { return "
  • " + esc(s.ref) + "
  • "; }).join("") + "
"; + } + + var VIEWS = { start: start, constructs: constructs, compare: compare, claims: claims, disagreements: disagreements, agenda: agenda, draft: draft, guide: guide }; + function route() { + var h = location.hash.replace(/^#/, "") || "start"; + var active = h.indexOf("c-") === 0 ? "constructs" : h; + var c = h.indexOf("c-") === 0 ? unhash(h.slice(2)) : null; + document.getElementById("nav").innerHTML = NAV.map(function (n) { + return '" + esc(n[1]) + ""; + }).join(""); + if (c) constructDetail(c); else (VIEWS[h] || start)(); + window.scrollTo(0, 0); + } + document.getElementById("foot").innerHTML = 'Kernel ' + esc(D.summary.kernel_version) + '. Generated from the compiler report of ' + esc(D.generatedAt.slice(0, 10)) + '. Source code, Apache-2.0.'; + window.addEventListener("hashchange", route); + route(); +})(); diff --git a/pipeline/lemma/site_assets/body.html b/pipeline/lemma/site_assets/body.html new file mode 100644 index 0000000..02f585c --- /dev/null +++ b/pipeline/lemma/site_assets/body.html @@ -0,0 +1,15 @@ +
+ +
+
+
+ + + diff --git a/pipeline/lemma/site_assets/head.html b/pipeline/lemma/site_assets/head.html new file mode 100644 index 0000000..4fd5b50 --- /dev/null +++ b/pipeline/lemma/site_assets/head.html @@ -0,0 +1,9 @@ +Lemma Explorer + + + + + + diff --git a/pipeline/lemma/site_assets/overlap.js b/pipeline/lemma/site_assets/overlap.js new file mode 100644 index 0000000..eefdb40 --- /dev/null +++ b/pipeline/lemma/site_assets/overlap.js @@ -0,0 +1,51 @@ +/* The overlap rule from Lemma/Meta/Overlap.lean, plus the draft renderer. + pipeline/tests/test_explore.py runs this file under Node against the compiler's own output. */ +(function (root, factory) { + var api = factory(); + if (typeof module === "object" && module.exports) module.exports = api; + else root.LemmaCore = api; +})(typeof self !== "undefined" ? self : this, function () { + function overlapKind(keysA, keysB) { + var a = new Set(keysA), b = new Set(keysB); + var shared = 0; + a.forEach(function (k) { if (b.has(k)) shared += 1; }); + if (shared === 0) return "none"; + if (shared === a.size && shared === b.size) return "identity"; + if (shared === a.size || shared === b.size) return "subtype"; + return "partial"; + } + + function fieldName(part) { + var pieces = part.split(" "); + return pieces[0].charAt(0).toLowerCase() + pieces[0].slice(1) + pieces.slice(1).join(""); + } + + function leanType(part) { + var pieces = part.split(" "); + return ["Lemma." + pieces[0]].concat(pieces.slice(1).map(function (a) { return "." + a; })).join(" "); + } + + function toIdentifier(text) { + var pieces = text.match(/[A-Za-z0-9]+/g) || []; + return pieces.map(function (p) { return p.charAt(0).toUpperCase() + p.slice(1); }).join(""); + } + + function docstring(definition, citation) { + var text = (definition.trim().replace(/\.+$/, "") + " (" + (citation.trim() || "citation to add") + ").").split(/\s+/).join(" "); + return text.replace(/-\//g, "- /").replace(/\/-/g, "/ -"); + } + + function renderLean(d) { + var imports = ["import Lemma"].concat(d.generated.map(function (m) { return "import Lemma.Generated." + m; })); + var fields = d.parts.map(function (p) { return " " + fieldName(p) + " : " + leanType(p); }); + return imports.concat([ + "", + "namespace Lemma.Drafts." + d.name, + "", + "/-- " + docstring(d.definition, d.citation) + " -/", + "@[construct] structure " + d.name + " extends " + d.category + " (level := ." + d.level + ") (horizon := ." + d.horizon + ") where" + ], fields, ["", "end Lemma.Drafts." + d.name, ""]).join("\n"); + } + + return { overlapKind: overlapKind, renderLean: renderLean, toIdentifier: toIdentifier }; +}); diff --git a/pipeline/lemma/site_assets/styles.css b/pipeline/lemma/site_assets/styles.css new file mode 100644 index 0000000..e08db60 --- /dev/null +++ b/pipeline/lemma/site_assets/styles.css @@ -0,0 +1,110 @@ +/* Layout concept: a table of parts, the way chemistry shows elements. Every construct is a formula over these tiles. */ +:root { + --bg: #edf1f3; --surface: #fbfcfd; --sunk: #e2e8eb; --ink: #13212b; --muted: #526470; --line: #c9d3d9; + --accent: #0b5cad; --accent-ink: #ffffff; --accent-soft: #d8e7f6; + --attn: #815400; --attn-bg: #fbf0d6; --bad: #a3262a; --bad-bg: #fbe6e4; --good: #1b6e4b; --good-bg: #dff3e8; + --ui: "Archivo", "Helvetica Neue", Arial, sans-serif; + --read: "Source Serif 4", Georgia, "Times New Roman", serif; + --mono: "JetBrains Mono", ui-monospace, Menlo, Consolas, monospace; +} +@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { + --bg: #0f171d; --surface: #172229; --sunk: #0b1217; --ink: #e6edf1; --muted: #9aabb5; --line: #2c3a43; + --accent: #6cb2f5; --accent-ink: #0b1c2b; --accent-soft: #17344e; + --attn: #e9be6a; --attn-bg: #33280f; --bad: #f29a95; --bad-bg: #3a1d1c; --good: #7fd3a9; --good-bg: #15301f; + color-scheme: dark; +} } +:root[data-theme="dark"] { + --bg: #0f171d; --surface: #172229; --sunk: #0b1217; --ink: #e6edf1; --muted: #9aabb5; --line: #2c3a43; + --accent: #6cb2f5; --accent-ink: #0b1c2b; --accent-soft: #17344e; + --attn: #e9be6a; --attn-bg: #33280f; --bad: #f29a95; --bad-bg: #3a1d1c; --good: #7fd3a9; --good-bg: #15301f; + color-scheme: dark; +} +* { box-sizing: border-box; } +body { margin: 0; background: var(--bg); color: var(--ink); font: 400 15px/1.5 var(--ui); } +body::before { content: ""; position: fixed; inset: 0 0 auto; height: env(safe-area-inset-top, 0px); z-index: 10; background: var(--surface); } +a { color: var(--accent); } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +h1, h2, h3 { font-family: var(--ui); text-wrap: balance; margin: 0; line-height: 1.12; } +h1 { font-size: clamp(2rem, 5.2vw, 3.4rem); font-weight: 800; font-stretch: 78%; letter-spacing: -.01em; } +h2 { font-size: 1.5rem; font-weight: 700; font-stretch: 85%; } +h3 { font-size: 1.02rem; font-weight: 650; } +p { margin: 0; } +.band { position: sticky; top: env(safe-area-inset-top, 0px); z-index: 5; background: var(--surface); border-bottom: 1px solid var(--line); } +.band-inner, main, .foot > div { max-width: 1160px; margin-inline: auto; } +.band-inner { display: flex; align-items: center; gap: 20px; padding-block: 10px; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); } +.brand { display: flex; align-items: center; gap: 9px; font-weight: 700; font-stretch: 85%; color: var(--ink); text-decoration: none; white-space: nowrap; } +.brand-mark { display: grid; place-items: center; width: 28px; height: 28px; background: var(--accent); color: var(--accent-ink); font: 600 13px var(--mono); } +nav { display: flex; gap: 2px; overflow-x: auto; min-width: 0; scrollbar-width: none; } +nav a { padding: 6px 10px; color: var(--muted); text-decoration: none; font-weight: 550; white-space: nowrap; } +nav a:hover { color: var(--ink); } +nav a[aria-current="page"] { color: var(--ink); box-shadow: inset 0 -2px 0 var(--accent); } +main { display: grid; gap: 34px; padding-block: 28px 56px; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); outline: none; } +section { display: grid; gap: 14px; min-width: 0; } +.lede { display: grid; gap: 12px; max-width: 46rem; } +.lede p { font-size: 1.1rem; color: var(--muted); } +.note { color: var(--muted); max-width: 46rem; } +.head-row { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: end; gap: 10px; } +.status { background: var(--attn-bg); color: var(--attn); padding: 10px 14px; max-width: 60rem; } +.stats { display: flex; flex-wrap: wrap; gap: 8px 28px; } +.stats b { display: block; font: 600 1.5rem/1.1 var(--mono); font-variant-numeric: tabular-nums; } +.stats span { color: var(--muted); font-size: .86rem; } +.table-of-parts { display: grid; grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); gap: 4px; } +.tile { display: grid; gap: 2px; align-content: start; padding: 8px 9px 9px; min-height: 92px; text-align: left; border: 0; cursor: pointer; color: var(--ink); font: inherit; + background: color-mix(in srgb, var(--accent) calc(var(--heat) * 34%), var(--surface)); } +.tile:hover { box-shadow: inset 0 0 0 2px var(--accent); } +.tile .n { font: 400 .72rem var(--mono); justify-self: end; color: var(--muted); grid-row: 1; grid-column: 2; } +.tile .sym { font: 600 1.5rem/1 var(--mono); grid-row: 1; grid-column: 1; } +.tile .nm { font-size: .8rem; line-height: 1.2; grid-column: 1 / 3; } +.findings { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 22px 28px; } +.finding { display: grid; gap: 6px; align-content: start; min-width: 0; border-top: 2px solid var(--ink); padding-top: 9px; } +.finding p { font-family: var(--read); font-size: 1rem; } +.finding .caution { font-family: var(--ui); font-size: .87rem; color: var(--attn); } +.linkish { background: none; border: 0; padding: 0; color: var(--accent); font: inherit; font-weight: 600; cursor: pointer; text-align: left; text-decoration: underline; text-underline-offset: 2px; } +.collections { display: grid; gap: 12px; } +.collection { display: grid; gap: 5px; } +.collection span { color: var(--muted); } +.controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: end; } +label.f { display: grid; gap: 3px; font-size: .78rem; font-weight: 600; color: var(--muted); min-width: 0; } +input, select, textarea { font: 400 .95rem var(--ui); color: var(--ink); background: var(--surface); border: 1px solid var(--line); padding: 7px 9px; min-width: 0; max-width: 100%; } +textarea { width: 100%; min-height: 66px; resize: vertical; font-family: var(--read); } +.btn { font: 600 .9rem var(--ui); padding: 7px 12px; background: var(--surface); color: var(--ink); border: 1px solid var(--ink); cursor: pointer; } +.btn:hover { background: var(--accent-soft); } +.btn.primary { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); } +.scroll { overflow-x: auto; background: var(--surface); border: 1px solid var(--line); } +table { border-collapse: collapse; width: 100%; font-size: .9rem; } +th { text-align: left; font-size: .75rem; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); padding: 8px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; } +td { padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; } +tr:last-child td { border-bottom: 0; } +td.num { font-family: var(--mono); font-variant-numeric: tabular-nums; } +tr.row { cursor: pointer; } +tr.row:hover td { background: var(--accent-soft); } +.chips { display: flex; flex-wrap: wrap; gap: 3px; } +.chip { display: inline-flex; gap: 5px; align-items: baseline; padding: 1px 7px 1px 0; background: var(--sunk); font-size: .8rem; white-space: nowrap; } +.chip b { font: 600 .74rem var(--mono); background: var(--accent); color: var(--accent-ink); padding: 1px 5px; } +.chip.shared b { background: var(--good); } +.chip button { border: 0; background: none; color: var(--muted); cursor: pointer; font: inherit; padding: 0 0 0 3px; } +.pill { display: inline-block; padding: 0 7px; font-size: .76rem; font-weight: 600; white-space: nowrap; background: var(--sunk); color: var(--muted); } +.pill.fixture { background: var(--attn-bg); color: var(--attn); } +.pill.identity, .pill.Negative, .pill.contradiction { background: var(--bad-bg); color: var(--bad); } +.pill.subtype, .pill.Curvilinear, .pill.partial { background: var(--attn-bg); color: var(--attn); } +.pill.Positive, .pill.none-kind { background: var(--good-bg); color: var(--good); } +.detail { display: grid; gap: 14px; background: var(--surface); border: 1px solid var(--line); padding: 18px; min-width: 0; } +.definition { font-family: var(--read); font-size: 1.1rem; line-height: 1.5; max-width: 42rem; } +.meta { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.split { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 14px; } +.split > div { display: grid; gap: 6px; align-content: start; min-width: 0; } +.eyebrow { font-size: .75rem; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); font-weight: 600; } +.verdict { display: grid; gap: 4px; } +.verdict strong { font-size: 1.25rem; font-stretch: 85%; } +pre.code { margin: 0; padding: 12px; overflow-x: auto; background: var(--sunk); font: 400 .82rem/1.5 var(--mono); } +.draft { display: grid; grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); gap: 24px; align-items: start; } +.form { display: grid; gap: 10px; min-width: 0; } +.form .row2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 8px; } +.form input, .form select { width: 100%; } +.results { display: grid; gap: 14px; min-width: 0; } +.empty { color: var(--muted); padding: 14px; } +ul.plain { margin: 0; padding: 0; list-style: none; display: grid; gap: 8px; } +details summary { cursor: pointer; font-weight: 600; } +.foot { border-top: 1px solid var(--line); color: var(--muted); font-size: .84rem; padding-block: 16px; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); } +@media (max-width: 760px) { .draft { grid-template-columns: minmax(0, 1fr); } .band-inner { flex-wrap: wrap; gap: 6px; } nav { width: 100%; } } +@media (prefers-reduced-motion: no-preference) { .tile { transition: box-shadow .12s; } } diff --git a/pipeline/pyproject.toml b/pipeline/pyproject.toml index dc3b7c6..5c5a52c 100644 --- a/pipeline/pyproject.toml +++ b/pipeline/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "lemma-pipeline" -version = "0.1.0" +version = "0.2.0" description = "AI formalization pipeline, compiler report generator and verification-priority scorer for the Lemma type system" readme = "README.md" requires-python = ">=3.11" @@ -24,7 +24,7 @@ where = ["."] include = ["lemma*"] [tool.setuptools.package-data] -lemma = ["prompts/*.md"] +lemma = ["prompts/*.md", "site_assets/*"] [tool.ruff] line-length = 120 diff --git a/pipeline/tests/test_explore.py b/pipeline/tests/test_explore.py new file mode 100644 index 0000000..9a2321b --- /dev/null +++ b/pipeline/tests/test_explore.py @@ -0,0 +1,291 @@ +"""The plain-language views, held to the compiler's own output in reports/library.json.""" + +from __future__ import annotations + +import itertools +import json +import shutil +import subprocess +from pathlib import Path + +import pytest + +from lemma.check import generated_modules +from lemma.cli import main +from lemma.config import Paths +from lemma.doctor import Check, render +from lemma.draft import ( + all_parts, + docstring, + explain, + library_built, + parse_catalog, + render_lean, + to_identifier, +) +from lemma.explore import ( + AmbiguousNameError, + Library, + UnknownNameError, + fill_counts, + load_curation, + overlap_kind, + theory_name, +) +from lemma.lean import LeanMessage, lean_check_file, toolchain_available +from lemma.site import ASSETS, build_data, build_site, render_page + +ROOT = Path(__file__).resolve().parents[2] +PATHS = Paths(ROOT) + + +@pytest.fixture(scope="module") +def lib(): + return Library(PATHS) + + +@pytest.fixture(scope="module") +def data(): + return build_data(PATHS) + + +def catalog(): + return parse_catalog((ROOT / "Lemma" / "Library" / "Primitives.lean").read_text(encoding="utf-8")) + + +def test_overlap_rule_matches_every_compiler_report(lib): + reported = {frozenset((o["a"], o["b"])): o["kind"] for o in lib.report["overlaps"]} + for a, b in itertools.combinations(lib.by_name, 2): + kind = overlap_kind(lib.keys[a], lib.keys[b]) + pair = frozenset((a, b)) + if pair in reported: + assert kind == reported[pair], (a, b) + elif kind != "none": + # The compiler skips a construct's own components by design. + components = [*lib.by_name[a].get("components", []), *lib.by_name[b].get("components", [])] + assert a in components or b in components, (a, b) + + +def test_resolve_prefers_the_lone_curated_entry(lib): + assert theory_name(lib.resolve("Vitality")["name"]) == "Thriving.Vitality" + assert theory_name(lib.resolve("engagement.vigor")["name"]) == "Engagement.Vigor" + + +def test_resolve_reports_ambiguity_and_absence(lib): + with pytest.raises(UnknownNameError): + lib.resolve("Zzz") + with pytest.raises(AmbiguousNameError): + _ambiguous(lib) + + +def _ambiguous(lib): + # Two fixture entries with one short name and no curated entry would be ambiguous. + original = lib.constructs + twin = {**original[0], "name": "Lemma.Generated.A.Twin", "module": "Lemma.Generated.A"} + other = {**original[0], "name": "Lemma.Generated.B.Twin", "module": "Lemma.Generated.B"} + lib.constructs = [*original, twin, other] + try: + lib.resolve("Twin") + finally: + lib.constructs = original + + +def test_exhaustion_and_vigor_comparison(lib): + cmp = lib.compare(lib.resolve("Burnout.Exhaustion"), lib.resolve("Engagement.Vigor")) + assert cmp.kind == "identity" + assert cmp.shared == ["Energy"] + assert cmp.declaration["kind"] == "distinct_from" + assert cmp.correlation["status"] == "placeholder" + + +def test_curation_names_resolve(lib): + curation = load_curation(PATHS) + views = {"disagreements", "agenda"} + for finding in curation["findings"]: + assert finding["caution"] + fill_counts(finding["title"], lib.report) + if "compare" in finding: + for name in finding["compare"]: + lib.resolve(name) + else: + assert finding["view"] in views + for collection in curation["collections"]: + for name in collection["constructs"]: + assert theory_name(lib.resolve(name)["name"]) == name + + +def test_curated_counts_come_from_the_report(lib): + titles = [fill_counts(f["title"], lib.report) for f in load_curation(PATHS)["findings"]] + assert "85 implied pairs lack a direct claim in the library" in titles + assert "3 of 9 pipeline papers were refused" in titles + + +def test_catalog_covers_the_vocabulary(lib): + entries = catalog() + assert len(entries) == lib.report["summary"]["primitives"] + parts = set(all_parts(entries)) + used = { + " ".join([p.split(".")[-1] for p in [leaf["prim"], *leaf["args"]]]) + for c in lib.constructs + for leaf in c["leaves"] + } + assert used <= parts + + +def test_identifier_and_docstring_safety(): + assert to_identifier("work vitality") == "WorkVitality" + with pytest.raises(ValueError): + to_identifier("123") + assert "-/" not in docstring("Ends the comment -/ early", "A /- B") + assert docstring("A definition.", "") == "A definition (citation to add)." + + +@pytest.mark.parametrize( + ("data_text", "severity", "expected"), + [ + ( + "shares primitive Energy with Engagement.vigor\n overlap kind: partial (1 of 2)", + "warning", + "Shares Energy with Engagement", + ), + ( + "shares primitives Energy, Learning with Thriving ∋ Vitality.energy", + "warning", + "Shares Energy, Learning with Thriving", + ), + ( + "construct `Bad` does not reduce to primitives\n Nat at count", + "error", + "Bad uses something outside the vocabulary", + ), + ("construct `Bad` requires a citation docstring (see CONTRIBUTING.md)", "error", "A citation is missing"), + ("scope mismatch in `p`: X lives at Team", "error", "The scope of p does not line up"), + ("contradicts q (JDR): A → B is Negative here", "warning", "This claim disagrees with another theory"), + ("something new", "information", "Compiler message"), + ], +) +def test_compiler_messages_are_explained(data_text, severity, expected): + assert explain(LeanMessage(severity, 1, 1, data_text)).headline == expected + + +def test_site_data_matches_the_report(data, lib): + s = lib.report["summary"] + assert len(data["constructs"]) == s["constructs"] + assert len(data["propositions"]) == s["propositions"] + assert len(data["overlaps"]) == s["overlap_warnings"] + assert len(data["catalog"]) == s["primitives"] + assert sum(1 for c in data["constructs"] if c["origin"] != "curated") == s["constructs_generated"] + + +def test_page_is_self_contained_and_safe(data, tmp_path): + hostile = {**data, "status": ""} + page = render_page(hostile) + assert "