From eb0c3464895e3927a18fd839179830a8319b66cb Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:45:17 -0500 Subject: [PATCH 01/28] feat(formal-verification): add the plugin skeleton, settings and toolchain scripts Register the formal-verification plugin (off by default) with its userConfig paths for the model checker jar, Java and the script runtime, prerequisites, README with the MIT notice for the carried statechart files, and the shared prerequisites and config-cascade copies. defaults.json holds the pins and bounds; scripts/settings.mjs resolves them through the consumer's docs/conventions/formal-verification.yaml. scripts/toolchain.mjs checks the toolchain, resolves it for the chart skill (blocked: toolchain missing when absent), and installs the pinned jar or renderer only when asked, keeping a download only when its checksum matches. Refs: #15648 Co-Authored-By: Claude Opus 5.5 --- ...ormal-verification-chart-setup-2f19b369.md | 11 + .claude-plugin/marketplace.json | 15 + docs/catalog.md | 1 + docs/skill-cheat-sheet.md | 1 + .../.claude-plugin/plugin.json | 39 + plugins/formal-verification/CHANGELOG.md | 4 + plugins/formal-verification/README.md | 126 +++ plugins/formal-verification/defaults.json | 24 + .../lib/config-cascade.mjs | 578 ++++++++++++++ .../formal-verification/lib/prerequisites.mjs | 745 ++++++++++++++++++ .../formal-verification/lib/prerequisites.ps1 | 50 ++ .../formal-verification/lib/prerequisites.sh | 62 ++ .../formal-verification/lib/yaml-subset.mjs | 313 ++++++++ .../formal-verification/prerequisites.json | 40 + .../schemas/formal-verification.schema.json | 53 ++ .../formal-verification/scripts/settings.mjs | 30 + .../formal-verification/scripts/toolchain.mjs | 173 ++++ .../scripts/toolchain.test.mjs | 136 ++++ .../scripts/toolchain.test.sh | 3 + scripts/fragment-plugins.txt | 1 + scripts/shared-copies.txt | 5 + 21 files changed, 2410 insertions(+) create mode 100644 .changes/formal-verification/feat-formal-verification-chart-setup-2f19b369.md create mode 100644 plugins/formal-verification/.claude-plugin/plugin.json create mode 100644 plugins/formal-verification/CHANGELOG.md create mode 100644 plugins/formal-verification/README.md create mode 100644 plugins/formal-verification/defaults.json create mode 100644 plugins/formal-verification/lib/config-cascade.mjs create mode 100755 plugins/formal-verification/lib/prerequisites.mjs create mode 100644 plugins/formal-verification/lib/prerequisites.ps1 create mode 100755 plugins/formal-verification/lib/prerequisites.sh create mode 100644 plugins/formal-verification/lib/yaml-subset.mjs create mode 100644 plugins/formal-verification/prerequisites.json create mode 100644 plugins/formal-verification/schemas/formal-verification.schema.json create mode 100755 plugins/formal-verification/scripts/settings.mjs create mode 100755 plugins/formal-verification/scripts/toolchain.mjs create mode 100644 plugins/formal-verification/scripts/toolchain.test.mjs create mode 100755 plugins/formal-verification/scripts/toolchain.test.sh diff --git a/.changes/formal-verification/feat-formal-verification-chart-setup-2f19b369.md b/.changes/formal-verification/feat-formal-verification-chart-setup-2f19b369.md new file mode 100644 index 00000000000..1f2b8583bc1 --- /dev/null +++ b/.changes/formal-verification/feat-formal-verification-chart-setup-2f19b369.md @@ -0,0 +1,11 @@ +--- +bump: minor +--- + +### Added + +- The `formal-verification` plugin, off by default. +- `/formal-verification:chart` model-checks a TLA+ spec with TLC and writes a Mermaid chart of its states and a report with the shortest path to each broken rule. Its scripts take the jar, Java and bounds as arguments and install nothing. +- `/formal-verification:setup` checks the script runtime, Java, the model checker and the renderer, and on a typed `apply install-model-checker` or `apply install-renderer` downloads the pinned file into the plugin data directory, keeping it only when its checksum matches. +- `reference/formal-skill.md`, the contract for a consumer's `formal-` skill: its sections, one `sync.yaml` entry per check, the view file the chart reads, and where model files and unattended writes may go. +- Version pins and default bounds as keys of the consumer's `docs/conventions/formal-verification.yaml`, and the jar, Java and script-runtime paths as plugin options. diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index ad92e1cb858..6c8817a74f5 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -611,6 +611,21 @@ "skill" ] }, + { + "name": "formal-verification", + "source": "./plugins/formal-verification", + "category": "testing", + "tags": [ + "formal-verification", + "tla-plus", + "tlc", + "model-checking", + "statechart", + "mermaid", + "skill" + ], + "defaultEnabled": false + }, { "name": "code-tidying", "source": "./plugins/code-tidying", diff --git a/docs/catalog.md b/docs/catalog.md index f28cf62e92c..afb178cce99 100644 --- a/docs/catalog.md +++ b/docs/catalog.md @@ -48,6 +48,7 @@ plugin manifests and kept in sync by CI. Never hand-edit it; the category vocabu - [`playwright`](../plugins/playwright): Live E2E browser automation via Microsoft's @playwright/cli: named sessions, accessibility-ref snapshots, click/fill by ref, screenshots, console and network capture, mocking, tracing, video, and auth state, with artifacts written to disk so only paths enter context, plus produced pull-request demo videos with frame-measured quality control, a vendored upstream baseline and maintainer drift-check update flow. - [`app-control`](../plugins/app-control): Runs the project's app and records evidence without judging it. /app-control:drive finds the project's control skill (or falls back to the bundled run skill or a project-type recipe), reports what is reachable, captures one artifact, stops only what it started, and writes report.md and report.json. /app-control:map writes and maintains that control skill: discovery first, questions only for what is left, and a driver CLI that enforces the safety floors. +- [`formal-verification`](../plugins/formal-verification): Formal verification for the part of a codebase where a bug costs most. /formal-verification:chart model-checks a TLA+ spec with TLC and draws its states as a Mermaid chart, with the shortest path to each broken rule for a person to judge. /formal-verification:setup checks the toolchain and installs the pinned, checksummed model checker only on a typed yes. A consumer's formal- skill follows reference/formal-skill.md. - [`tdd`](../plugins/tdd): A TDD knowledge base distilled from cover-to-cover readings of Kent Beck's Test-Driven Development: By Example and Vladimir Khorikov's Unit Testing: Principles, Practices, and Patterns. Fourteen author-attributed reference files behind a routing table, plus a no-load quick decision guide, answer the WHY behind test design decisions. - [`evals`](../plugins/evals): LLM evaluation methodology and eval-suite design, based on Anthropic's evaluation guidance. /evals:methodology answers questions on success criteria, eval design, and grading. /evals:design interviews for measurable success criteria and scaffolds a graded eval suite for an LLM app or Claude Code skill. /evals:plugin-eval preflights the CLI and target, prices a suite before running, and reads the with-versus-without delta. /evals:validate checks case files with no model call. - [`testing`](../plugins/testing): Test-stage discipline: /testing:plan (coverage gaps, test plans), /testing:write (TDD authoring), /testing:run-e2e (live E2E and smoke checks), /testing:diagnose (failing-test root cause, with a fix-until-green workflow across files), /testing:audit (can't-fail test audit with a fail-closed gate), /testing:cleanup (rewrite, quarantine, or delete low-value tests behind a mutation gate), /testing:setup, and an opt-in hook that flags edits that weaken tests. diff --git a/docs/skill-cheat-sheet.md b/docs/skill-cheat-sheet.md index 7f89d660c0d..d3d94fe72d1 100644 --- a/docs/skill-cheat-sheet.md +++ b/docs/skill-cheat-sheet.md @@ -211,6 +211,7 @@ From the stage definitions: A conditional stage runs only when its trigger holds | Skill | Plugin | What it does | Actions | Arguments | Upstream | Next | | --- | --- | --- | --- | --- | --- | --- | +| [`/formal-verification:chart`](../plugins/formal-verification/skills/chart/SKILL.md) | `formal-verification` | Check a TLA+ spec with TLC, chart its states, path each broken rule | | ` [--view FILE] [--out DIR] [--chart-states N] [--rerun-states N] [--image…]` | | `/bugs:write`, `/verification:confirm` | | [`/performance:protect`](../plugins/performance/skills/protect/SKILL.md) | `performance` | Hold a verified counter win with a CI ceiling a human merges | | `[]` | | `/toolchain:ratchet`, `/source-control:pull-request` | | [`/performance:snapshot`](../plugins/performance/skills/snapshot/SKILL.md) | `performance` | Capture a snapshot only from a host proven measurable | `baseline`, `post` | `[baseline\|post] []` | [pstack `hillclimb`](upstream/cursor-pstack.md#attribution-table) | `/implementation:implement`, `/performance:snapshot`, `/performance:climb`, `/performance:verify` | | [`/performance:verify`](../plugins/performance/skills/verify/SKILL.md) | `performance` | Re-derive the result in fresh context and report it honestly | | `[]` | [pstack `principle-explain-the-number`](upstream/cursor-pstack.md#attribution-table), [pstack `benchmark-checklist`](upstream/cursor-pstack.md#attribution-table) | `/performance:protect`, `/source-control:pull-request`, `/performance:target`, `/debugging:debug` | diff --git a/plugins/formal-verification/.claude-plugin/plugin.json b/plugins/formal-verification/.claude-plugin/plugin.json new file mode 100644 index 00000000000..72ef2fcaa25 --- /dev/null +++ b/plugins/formal-verification/.claude-plugin/plugin.json @@ -0,0 +1,39 @@ +{ + "name": "formal-verification", + "description": "Formal verification for the part of a codebase where a bug costs most. /formal-verification:chart model-checks a TLA+ spec with TLC and draws its states as a Mermaid chart, with the shortest path to each broken rule for a person to judge. /formal-verification:setup checks the toolchain and installs the pinned, checksummed model checker only on a typed yes. A consumer's formal- skill follows reference/formal-skill.md.", + "author": { + "name": "Melodic Software", + "email": "info@melodicsoftware.com" + }, + "version": "0.0.0", + "license": "MIT", + "keywords": [ + "formal-verification", + "tla-plus", + "tlc", + "model-checking", + "statechart", + "mermaid", + "skill" + ], + "metadata": { + "category": "testing" + }, + "userConfig": { + "model_checker_jar": { + "type": "file", + "title": "Model checker jar", + "description": "Path to tla2tools.jar, the TLC model checker. Unset uses the jar that setup installs under the plugin data directory." + }, + "java": { + "type": "file", + "title": "Java binary", + "description": "Path to the java binary that runs TLC. Unset uses java on PATH. The plugin never installs Java." + }, + "script_runtime": { + "type": "file", + "title": "Script runtime", + "description": "Path to the Node, Bun or Deno binary that runs the chart scripts. Unset lets the launcher pick the first supported one on PATH." + } + } +} diff --git a/plugins/formal-verification/CHANGELOG.md b/plugins/formal-verification/CHANGELOG.md new file mode 100644 index 00000000000..25082eabf73 --- /dev/null +++ b/plugins/formal-verification/CHANGELOG.md @@ -0,0 +1,4 @@ +# Changelog + +All notable changes to the `formal-verification` plugin are documented here. Format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this plugin uses semantic versioning. diff --git a/plugins/formal-verification/README.md b/plugins/formal-verification/README.md new file mode 100644 index 00000000000..b80bb3ae676 --- /dev/null +++ b/plugins/formal-verification/README.md @@ -0,0 +1,126 @@ +# formal-verification + +Formal verification for the part of a codebase where a bug costs most and tests reach least. +`/formal-verification:chart` checks a TLA+ model with TLC, draws its states as a Mermaid chart, and +gives the shortest path to each rule that breaks, for a person to judge. A consumer keeps each model +in its own `formal-` skill, shaped by [`reference/formal-skill.md`](reference/formal-skill.md). + +## Install + +```shell +/plugin marketplace add melodic-software/claude-code-plugins +/plugin install formal-verification@melodic-software +``` + +## Skills + +| Skill | What it does | +|---|---| +| `/formal-verification:chart` | Model-checks a TLA+ spec with TLC and writes `chart.mmd` and `report.md`: each rule that holds, each that breaks with its shortest path, and the rules a bound left unchecked. Model-invoked too, so a `formal-` skill's Run can call it. | +| `/formal-verification:setup` | `check` reports the script runtime, Java, the model checker and the renderer; `apply install-model-checker` and `apply install-renderer` download the pinned file into the plugin data directory and keep it only when its checksum matches. Typed only. | + +## Configuration + +Machine paths are plugin options, set through `/plugin configure`: the model checker jar, the Java +binary and the script runtime (the options block below). + +Version pins and default bounds are keys in the consumer's +`docs/conventions/formal-verification.yaml`, checked against +[`schemas/formal-verification.schema.json`](schemas/formal-verification.schema.json). An absent key +takes the shipped value in [`defaults.json`](defaults.json). `scripts/settings.mjs` prints the +resolved values: + +```shell +node /scripts/settings.mjs --project-dir . +``` + +A bound for one model goes in that model's run command (`--chart-states`, `--rerun-states`), in its +`formal-` skill. + +## Prerequisites + +| Tool | Who installs it | +|---|---| +| A script runtime: Node, Bun or Deno (the launcher names the versions it accepts) | You. | +| Java (the `java.min_version` setting) | You. The plugin never installs Java. | +| The TLC model checker, `tla2tools.jar` | `/formal-verification:setup apply install-model-checker`, on your typed request, from the pinned URL and SHA-256. Or point the model checker jar option at your own. | +| The Pele renderer, only for an image of a chart | `/formal-verification:setup apply install-renderer`, from the pinned tarball and integrity string. | + +No script installs anything while a skill runs, and an unattended run that finds the toolchain +missing reports `blocked: toolchain missing` and stops. `prerequisites.json` declares the runtime, +Java and the renderer for `/harness-ops:prerequisites`; the jar is a file in the plugin data +directory, which that checker has no kind for, so `scripts/toolchain.mjs check` checks it. + +## Tests + +`node --test scripts/toolchain.test.mjs` covers settings resolution and the toolchain check and +install. The chart scripts carry their own suite under `skills/chart/scripts/test/`. + + + +### Options reference + +Generated from this plugin's `.claude-plugin/plugin.json`. For how Claude Code asks for +these and hands them to the plugin, see [User configuration](https://code.claude.com/docs/en/plugins/manifest-reference#user-configuration). + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `model_checker_jar` | file | *(none)* | Path to tla2tools.jar, the TLC model checker. Unset uses the jar that setup installs under the plugin data directory. | +| `java` | file | *(none)* | Path to the java binary that runs TLC. Unset uses java on PATH. The plugin never installs Java. | +| `script_runtime` | file | *(none)* | Path to the Node, Bun or Deno binary that runs the chart scripts. Unset lets the launcher pick the first supported one on PATH. | + +### How to set these + +Set the options above for `formal-verification@`, replacing `` with the +marketplace you installed this plugin from: + +- **In a session or headless:** [`/plugin` in a session](https://code.claude.com/docs/en/plugins/cli-reference#plugin-in-a-session) or + [`claude plugin configure`](https://code.claude.com/docs/en/plugins/cli-reference#plugin-configure). The configure command is the preferred + headless route in the [plugin-reconfiguration convention](https://github.com/melodic-software/claude-code-plugins/blob/main/docs/contracts/plugin-reconfiguration/README.md), which records its limits. +- **By hand:** under [`pluginConfigs`](https://code.claude.com/docs/en/settings-reference#pluginconfigs) in your **user** settings. + +Do **not** uninstall the plugin to reconfigure it: see [What an uninstall deletes and keeps](https://code.claude.com/docs/en/plugins/cli-reference#what-an-uninstall-deletes-and-keeps). +For a Claude Code release without `plugin configure`, see [Plugin install](https://code.claude.com/docs/en/plugins/cli-reference#plugin-install). + +### Upstream documentation + +- [User configuration](https://code.claude.com/docs/en/plugins/manifest-reference#user-configuration) +- [Plugin configure](https://code.claude.com/docs/en/plugins/cli-reference#plugin-configure) +- [Plugin install options](https://code.claude.com/docs/en/plugins/cli-reference#plugin-install) +- [Plugins and skills settings](https://code.claude.com/docs/en/settings-reference#plugins-and-skills) +- [Settings files and who they affect](https://code.claude.com/docs/en/settings#settings-files-and-who-they-affect) +- [Manage installed plugins](https://code.claude.com/docs/en/plugins/install#manage-installed-plugins) + + + +## Attribution + +`/formal-verification:chart` carries the `statechart` skill of pstack in +[cursor/plugins](https://github.com/cursor/plugins), its text and its scripts, changed so that the +scripts take the jar, Java and bounds as arguments and install nothing. The record is +[`docs/upstream/cursor-pstack.md`](../../docs/upstream/cursor-pstack.md). Those files are used under +this license: + +```text +MIT License + +Copyright (c) 2026 Lauren Tan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/plugins/formal-verification/defaults.json b/plugins/formal-verification/defaults.json new file mode 100644 index 00000000000..31061f78d7c --- /dev/null +++ b/plugins/formal-verification/defaults.json @@ -0,0 +1,24 @@ +{ + "model_checker": { + "version": "1.7.4", + "url": "https://github.com/tlaplus/tlaplus/releases/download/v1.7.4/tla2tools.jar", + "sha256": "936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88" + }, + "java": { + "min_version": "11", + "distribution": "temurin-25" + }, + "renderer": { + "package": "pele", + "version": "1.9.0", + "url": "https://registry.npmjs.org/pele/-/pele-1.9.0.tgz", + "integrity": "sha512-KUmBt7P5JduVKQaP6FKfXiRgH3LBVIKsmdgPJZU7jD3ye6F+Z8fbms+OjivE7rWY09Qx+5X65VKe/9ywKFJ9Sw==", + "limit": 1000000, + "output_limit": 8000000, + "max_edges": 10000 + }, + "bounds": { + "chart_states": 500, + "rerun_states": 100000 + } +} diff --git a/plugins/formal-verification/lib/config-cascade.mjs b/plugins/formal-verification/lib/config-cascade.mjs new file mode 100644 index 00000000000..b3deb636513 --- /dev/null +++ b/plugins/formal-verification/lib/config-cascade.mjs @@ -0,0 +1,578 @@ +// GENERATED from lib/config-cascade.mjs by scripts/sync-shared-copies.sh. Do not edit this copy: +// edit the canonical source, then rerun the script. +// The four-layer plugin config cascade (docs/adr/0075): later layers win per key. +// +// resolve({plugin, projectRoot, home, schema, defaults, userConfig, teamOnly, floors, userHome}) +// -> {values, provenance: {"a.b": layer | [layers]}, prose: [paths], sections: [{heading, text, layer}], +// layers: [{name, path, state: "loaded" | "absent" | "invalid", errors, error_keys}], legacy: [{path, kind}]} +// +// readLayers({...}) -> each layer's own accepted values, unmerged (see its comment below) +// +// `error_keys[i]` tags `errors[i]`: the dotted key the error names (key-level), or null when it is +// about the layer as a whole (file-level: a file refused or unparsable, a value that is not a mapping). +// +// Layers, in order: "defaults" (the `defaults` object, already parsed by the caller), "userConfig" +// (the plugin's userConfig values, flattened names), "team" (/) and "local", the +// personal override (/.local). A file layer reads .yaml for config and .md +// for prose; it is absent when neither file exists. `home` is the convention home the caller +// resolved, relative to projectRoot unless absolute (default docs/conventions). There is no +// user-global file layer: a file under /docs/conventions is never read, and `userHome` +// (default os.homedir()) only locates the legacy files reported in `legacy`. `schema` is a JSON +// Schema object; the subset honored is type (object, string, array, null, integer, number, boolean), +// enum, properties, additionalProperties (false or a schema), items, minimum, maximum, minItems and +// maxItems. +// +// A key is a schema leaf: any node that is not an object with `properties`, or a path named in +// `teamOnly`. The setup writer's top-level `written_against` and `provenance` records are not keys, +// declared or not: every layer skips them, so they reach neither `values` nor a userConfig name. +// Each layer's leaves are checked one by one; a leaf whose value fails the schema is +// dropped from that layer with an error naming layer, file and key, and a lower layer's value is +// then never used (ADR 0075, the invalid-value rule): a valid higher layer still wins, otherwise the +// key takes its default. The personal override is the one exception, because it refines the team +// file: an invalid personal value leaves the team value standing. A key containing `.` is +// rejected the same way, since keys are joined with `.` into paths, and so are `__proto__`, +// `constructor` and `prototype`, at any depth inside a value too, which a caller's merge would treat +// as more than data. A refused file makes its layer invalid; the layer's other file still applies. The team and +// local layers come from the repository: each reads only regular files, never a symlink, and is +// invalid when a relative `home` resolves outside projectRoot. A team-only key is +// accepted in "defaults" and "team" and rejected elsewhere. A YAML file that does not parse, or +// whose top level is not a mapping, makes its layer invalid and contributes no values; its .md +// file still supplies prose. A leaf whose last segment is `disable` and whose value is a list is the +// union of every layer's list, and its provenance is an array of the layer names that set it, in +// layer order; every other key's provenance is a single layer-name string. +// +// Policy floors. `floors` maps a key path to a `Floor direction` value (the Implementers table of +// docs/contracts/config-cascade/README.md; the closed set is no-floor, team-only, lowest-value, +// any-layer-wins and stricter-value), or to {direction, scale} where stricter-value takes a scale +// from loosest to strictest (default: the leaf's schema `enum` order). When the team layer set a +// floor key, a personal value is accepted only if it is no looser in that direction: team-only takes +// an equal value (a list must keep every team item); lowest-value a number no higher; any-layer-wins +// a tightening value (`true` or "report") whenever the team value is one; stricter-value a value at +// or beyond the team value on the scale. A looser value is dropped with an error naming the layer, +// file and key, and the team value stands. Floors bind the personal override; a `*.disable` union key +// is not compared. +// +// userConfig maps each schema leaf path to its name joined with `_` (widget.limit is widget_limit); +// two leaves with one name throw. An empty string or an unrendered `${user_config.` placeholder is +// unset, names outside the schema are ignored, and a list, mapping or team-only key is rejected. +// A string value takes the leaf's integer, number or boolean type when the leaf does not accept +// strings. Legacy locations (.claude/.* under userHome and projectRoot, and a fenced +// `yaml config` block in the team .md) are reported in `legacy`, never read for values. +// +// Prose. A `.local.md` H2 section (a `## ` heading outside a code fence) replaces the team `.md` +// section with the same heading; every other team section is kept, a local section with a new +// heading follows them, and the team text before the first H2 is kept. `sections` lists the result in +// order, each with the layer it came from (`heading` is null for text before the first H2). +// This module reads files only. File contents are data; error messages quote them as JSON strings. +import { lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs"; +import { homedir } from "node:os"; +import { isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path"; +import { parse } from "./yaml-subset.mjs"; + +const PLUGIN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const SCALARS = ["string", "integer", "number", "boolean", "null"]; +const DIRECTIONS = ["no-floor", "team-only", "lowest-value", "any-layer-wins", "stricter-value"]; +const clip = (text) => (text.length > 60 ? `${text.slice(0, 60)}...` : text); +const quote = (text) => JSON.stringify(clip(text)); +const show = (value) => clip(JSON.stringify(value) ?? String(value)); +const put = (object, key, value) => Object.defineProperty(object, key, { value, enumerable: true, writable: true, configurable: true }); +const isMapping = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const RESERVED = new Set(["__proto__", "constructor", "prototype"]); +const WRITER_KEYS = new Set(["written_against", "provenance"]); +const isWriterKey = (parts, key) => !parts.length && WRITER_KEYS.has(key); +const newLayer = (name, path, state, errors = [], error_keys = errors.map(() => null)) => ({ name, path, state, errors, error_keys }); +/** Records an error on `layer`, tagged with the dotted key it names, or null for a file-level one. */ +const record = (layer, message, key = null) => { + layer.errors.push(message); + layer.error_keys.push(key); +}; +/** Records `message` on `layer`, prefixed with the layer's name and path. */ +const recordOn = (layer, message, key) => record(layer, `${layer.name}${layer.path ? ` (${layer.path})` : ""}: ${message}`, key); + +function checkPlugin(plugin) { + if (typeof plugin !== "string" || !PLUGIN.test(plugin)) throw new Error(`config-cascade: plugin name ${JSON.stringify(plugin)} is not a plain name`); +} + +/** The convention home, whether a relative one escapes projectRoot, and the [name, stem] of each file layer. */ +function fileLayersOf(plugin, projectRoot, home) { + const homeDir = resolvePath(projectRoot, home); + // A relative home is inside the checkout by intent; a committed symlink must not carry it out. + const homeEscapes = !isAbsolute(home) && escapes(homeDir, projectRoot); + const stems = [ + ["team", join(homeDir, plugin)], + ["local", join(homeDir, `${plugin}.local`)], + ]; + return { homeDir, homeEscapes, stems }; +} + +const escapedLayer = (name, stem, homeDir) => + newLayer(name, `${stem}.yaml`, "invalid", [`${name} (${homeDir}): the convention home resolves outside the project; a repository layer stays inside it`]); + +/** {ok} for a readable repository layer file, {refused: why} for one that must not be read, {} when + * absent. A symlink is refused, since it could reach a file outside the checkout, and so is anything + * but a regular file, since a device or FIFO never finishes reading. */ +function fileState(path) { + let st; + try { + st = lstatSync(path); + } catch { + return {}; + } + if (st.isSymbolicLink()) return { refused: "is a symlink; a repository layer reads only regular files" }; + return st.isFile() ? { ok: true } : { refused: "is not a regular file" }; +} + +/** True when `dir` exists and its real path lies outside the real path of `root`. */ +function escapes(dir, root) { + try { + const rel = relative(realpathSync(root), realpathSync(dir)); + return rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel); + } catch { + return false; + } +} +const typesOf = (node) => (node.type === undefined ? null : [node.type].flat()); + +const fits = { + object: isMapping, + array: Array.isArray, + string: (v) => typeof v === "string", + integer: Number.isInteger, + number: (v) => typeof v === "number" && Number.isFinite(v), + boolean: (v) => typeof v === "boolean", + null: (v) => v === null, +}; + +/** The schema for `key` under `node`: a schema, null when anything goes, false when it is unknown. */ +function child(node, key) { + if (isMapping(node.properties) && Object.hasOwn(node.properties, key)) return node.properties[key]; + if (node.additionalProperties === false) return false; + return isMapping(node.additionalProperties) ? node.additionalProperties : null; +} + +const isBranch = (node, path, teamOnly) => + isMapping(node) && isMapping(node.properties) && !teamOnly.has(path) && (typesOf(node)?.includes("object") ?? true); + +/** Why `value` does not fit `node`, as messages relative to the key; empty when it fits. */ +function check(value, node, at = "") { + const prefix = at ? `${at}: ` : ""; + const types = typesOf(node); + if (types && !types.some((t) => fits[t]?.(value))) return [`${prefix}expected ${types.join(" or ")}, got ${show(value)}`]; + if (Array.isArray(node.enum) && !node.enum.includes(value)) return [`${prefix}${show(value)} is not one of ${node.enum.map(show).join(", ")}`]; + if (typeof value === "number" && typeof node.minimum === "number" && value < node.minimum) return [`${prefix}${show(value)} must be at least ${node.minimum}`]; + if (typeof value === "number" && typeof node.maximum === "number" && value > node.maximum) return [`${prefix}${show(value)} must be at most ${node.maximum}`]; + if (Array.isArray(value) && typeof node.minItems === "number" && value.length < node.minItems) return [`${prefix}needs at least ${node.minItems} items, got ${value.length}`]; + if (Array.isArray(value) && typeof node.maxItems === "number" && value.length > node.maxItems) return [`${prefix}allows at most ${node.maxItems} items, got ${value.length}`]; + // An open node ({}) checks nothing but reserved names, which are refused at every depth. + if (Array.isArray(value)) return value.flatMap((item, i) => check(item, isMapping(node.items) ? node.items : {}, `${at}[${i}]`)); + if (!isMapping(value)) return []; + return Object.keys(value).flatMap((key) => { + const where = `${at}.${quote(key)}`; + if (RESERVED.has(key)) return [`${where}: a reserved name, never a config key`]; + const sub = child(node, key); + if (sub === false) return [`${where}: unknown key`]; + return check(value[key], sub ?? {}, where); + }); +} + +/** The accepted leaves of one layer's mapping, as [parts, value] pairs; rejections go to `fail` + * with the dotted key, and `true` third when the value itself was the problem. */ +function leaves(data, schema, { teamOnly, allowTeamOnly, fail }) { + const out = []; + const walk = (object, node, parts) => { + for (const key of Object.keys(object)) { + if (isWriterKey(parts, key)) continue; + const path = [...parts, key]; + const dotted = path.join("."); + const sub = child(node, key); + const value = object[key]; + if (RESERVED.has(key)) fail(`${quote(dotted)}: a reserved name, never a config key`, dotted); + else if (key.includes(".")) fail(`${quote(dotted)}: a key may not contain "."; nest it instead`, dotted); + else if (sub === false) fail(`${quote(dotted)}: unknown key`, dotted); + else if (teamOnly.has(dotted) && !allowTeamOnly) fail(`${quote(dotted)}: accepted only in the team layer`, dotted); + else if (sub && isBranch(sub, dotted, teamOnly)) { + if (isMapping(value)) walk(value, sub, path); + else if (value !== null) fail(`${quote(dotted)}: expected a mapping, got ${show(value)}`, dotted, true); + } else { + const problems = check(value, sub ?? {}); + if (problems.length) fail(`${quote(dotted)}: ${problems.join("; ")}`, dotted, true); + else out.push([path, value]); + } + } + }; + walk(data, schema, []); + return out; +} + +/** Flattened userConfig name to {path, node} for every schema leaf. */ +function flatNames(schema, teamOnly) { + const names = new Map(); + const walk = (node, parts) => { + for (const key of Object.keys(isMapping(node.properties) ? node.properties : {})) { + if (isWriterKey(parts, key)) continue; + const path = [...parts, key]; + const dotted = path.join("."); + const sub = node.properties[key]; + if (isBranch(sub, dotted, teamOnly)) { + walk(sub, path); + continue; + } + const name = path.join("_"); + if (names.has(name)) throw new Error(`config-cascade: schema keys ${names.get(name).dotted} and ${dotted} both flatten to userConfig name ${name}`); + names.set(name, { path, dotted, node: sub }); + } + }; + walk(schema, []); + return names; +} + +function coerce(raw, node) { + const types = typesOf(node) ?? []; + if (typeof raw !== "string" || types.includes("string")) return raw; + if ((types.includes("integer") || types.includes("number")) && /^[-+]?\d+(\.\d+)?$/.test(raw)) return Number(raw); + if (types.includes("boolean") && (raw === "true" || raw === "false")) return raw === "true"; + return raw; +} + +function userConfigLeaves(userConfig, names, teamOnly, fail) { + const out = []; + for (const [name, raw] of Object.entries(userConfig)) { + if (raw === undefined || raw === null || raw === "" || (typeof raw === "string" && raw.startsWith("${user_config."))) continue; + const leaf = names.get(name); + if (!leaf) continue; + const types = typesOf(leaf.node); + if (teamOnly.has(leaf.dotted)) fail(`${quote(leaf.dotted)}: accepted only in the team layer`, leaf.dotted); + else if (types && !types.every((t) => SCALARS.includes(t))) fail(`${quote(leaf.dotted)}: lists and mappings are set only in files`, leaf.dotted); + else { + const value = coerce(raw, leaf.node); + const problems = check(value, leaf.node); + if (problems.length) fail(`${quote(leaf.dotted)}: ${problems.join("; ")}`, leaf.dotted, true); + else out.push([leaf.path, value]); + } + } + return out; +} + +/** One file layer: its report entry, its parsed mapping (or null), and its prose path (or null). */ +function readLayer(name, stem) { + const path = `${stem}.yaml`; + const md = `${stem}.md`; + const layer = newLayer(name, path, "absent"); + const mdFile = fileState(md); + if (mdFile.refused) { + layer.state = "invalid"; + record(layer, `${name} (${md}): ${mdFile.refused}`); + } + const prose = mdFile.ok ? md : null; + if (prose) layer.state = "loaded"; + const yamlFile = fileState(path); + if (yamlFile.refused) { + layer.state = "invalid"; + record(layer, `${name} (${path}): ${yamlFile.refused}`); + } + if (!yamlFile.ok) return { layer, data: null, prose }; + return { layer, data: parseInto(layer, () => readFileSync(path, "utf8")), prose }; +} + +/** The mapping `text()` parses to, loading `layer`; null, with the layer invalid, when it does not parse or is not a mapping. */ +function parseInto(layer, text) { + try { + const doc = parse(text()) ?? {}; + if (!isMapping(doc)) throw new Error("the top level must be a mapping"); + if (layer.state !== "invalid") layer.state = "loaded"; + return doc; + } catch (e) { + layer.state = "invalid"; + record(layer, `${layer.name} (${layer.path}): ${e.message}`); + return null; + } +} + +/** The body of the first ``` config block outside any other fence in a Markdown text, running to + * the end when unclosed; null when there is none. */ +export function configBlockBody(text) { + let fence = null; // the open fence's marker run, backticks or tildes + let body = null; + for (const line of text.split(/\r\n|\r|\n/)) { + const run = line.match(/^(`{3,}|~{3,})/)?.[0]; + if (fence) { + if (run?.[0] === fence[0] && run.length >= fence.length && line.trimEnd().length === run.length) { + if (body) return body.join("\n"); + fence = null; + } else body?.push(line); + } else if (/^```[A-Za-z0-9_-]+ config\s*$/.test(line)) [fence, body] = ["```", []]; + else if (run) fence = run; + } + return body?.join("\n") ?? null; +} + +/** True when the Markdown file holds a ``` config block outside any other fence. */ +function hasConfigBlock(path) { + const text = fileState(path).ok ? readText(path) : null; + return text !== null && configBlockBody(text) !== null; +} + +/** A Markdown text as [{heading, text}], split at each H2 outside a code fence; the first entry holds + * the text before the first H2 (heading null) and is dropped when empty. */ +function splitSections(text) { + const out = [{ heading: null, lines: [] }]; + let fence = null; + for (const line of text.split(/(?<=\n)/)) { + const run = line.match(/^ {0,3}(`{3,}|~{3,})/)?.[1]; + if (fence) { + if (run?.[0] === fence[0] && run.length >= fence.length && line.trim().length === run.length) fence = null; + } else if (run) fence = run; + else { + const h = line.match(/^## +(.*?)(?: +#+)?\s*$/); + if (h) { + out.push({ heading: h[1].replace(/\s+/g, " ").trim(), lines: [line] }); + continue; + } + } + out.at(-1).lines.push(line); + } + return out.map(({ heading, lines }) => ({ heading, text: lines.join("") })).filter((s) => s.heading !== null || s.text.trim() !== ""); +} + +function readText(path) { + try { + return readFileSync(path, "utf8"); + } catch { + return null; + } +} + +/** The team sections with each same-heading local section in its place, then the local sections the + * team lacks. The first team section with a heading is replaced; a later team repeat of it is dropped. */ +function mergeSections(teamText, localText) { + const team = teamText === null ? [] : splitSections(teamText).map((s) => ({ ...s, layer: "team" })); + const local = localText === null ? [] : splitSections(localText).map((s) => ({ ...s, layer: "local" })); + const replacement = new Map(local.filter((s) => s.heading !== null).map((s) => [s.heading, s])); + const used = new Set(); + const out = []; + for (const s of team) { + if (s.heading === null || !replacement.has(s.heading)) out.push(s); + else if (!used.has(s.heading)) { + used.add(s.heading); + out.push(replacement.get(s.heading)); + } + } + const teamHeadings = new Set(team.map((s) => s.heading)); + for (const s of local) { + // Text before the first H2 follows the team's own only when the team has no file; a repeated heading keeps its last section. + const fresh = s.heading === null ? team.length === 0 : !teamHeadings.has(s.heading) && replacement.get(s.heading) === s; + if (fresh) out.push(s); + } + return out; +} + +function legacyFiles(dir, plugin, kind) { + let entries; + try { + entries = readdirSync(dir, { withFileTypes: true }); + } catch { + return []; + } + return entries.filter((e) => e.isFile() && e.name.startsWith(`${plugin}.`)).map((e) => ({ path: join(dir, e.name), kind: kind(e.name) })); +} + +function setPath(object, parts, value) { + let at = object; + for (const part of parts.slice(0, -1)) { + if (!Object.hasOwn(at, part) || !isMapping(at[part])) put(at, part, {}); + at = at[part]; + } + put(at, parts.at(-1), value); +} + +/** Validated floors: dotted key to {direction, scale}. */ +function normalizeFloors(floors) { + if (!isMapping(floors)) throw new Error("config-cascade: floors must be a mapping of key path to Floor direction"); + const out = new Map(); + for (const [key, raw] of Object.entries(floors)) { + const direction = typeof raw === "string" ? raw : raw?.direction; + if (!DIRECTIONS.includes(direction)) throw new Error(`config-cascade: floor ${JSON.stringify(key)} has direction ${show(direction)}, not one of ${DIRECTIONS.join(", ")}`); + out.set(key, { direction, scale: isMapping(raw) && Array.isArray(raw.scale) ? raw.scale : null }); + } + return out; +} + +function nodeAt(schema, parts) { + let node = schema; + for (const part of parts) { + node = node && child(node, part); + if (!node) return null; + } + return node; +} + +const tightening = (v) => v === true || v === "report"; + +/** Why `personal` loosens `team` in the floor's direction, or null when it does not. */ +function looser(floor, personal, team, node) { + if (JSON.stringify(personal) === JSON.stringify(team)) return null; + switch (floor.direction) { + case "team-only": + if (Array.isArray(personal) && Array.isArray(team) && team.every((t) => personal.some((p) => JSON.stringify(p) === JSON.stringify(t)))) return null; + return `${show(personal)} differs from the team value ${show(team)}, and the team value wins`; + case "lowest-value": + if (typeof personal === "number" && typeof team === "number" && personal <= team) return null; + return `${show(personal)} is not lower than or equal to the team value ${show(team)}`; + case "any-layer-wins": + if (!tightening(team) || tightening(personal)) return null; + return `${show(personal)} drops the team value ${show(team)}, which is the tightening one`; + case "stricter-value": { + const scale = floor.scale ?? node?.enum ?? []; + const a = scale.findIndex((v) => JSON.stringify(v) === JSON.stringify(personal)); + const b = scale.findIndex((v) => JSON.stringify(v) === JSON.stringify(team)); + if (a >= 0 && b >= 0 && a >= b) return null; + return `${show(personal)} is not as strict as the team value ${show(team)} on the scale ${show(scale)}`; + } + default: + return null; + } +} + +export function resolve({ plugin, projectRoot, home = "docs/conventions", schema, defaults, userConfig, teamOnly = [], floors = {}, userHome = homedir() }) { + checkPlugin(plugin); + const only = new Set(teamOnly); + const floorMap = normalizeFloors(floors); + const names = flatNames(schema, only); + const { homeDir, homeEscapes, stems } = fileLayersOf(plugin, projectRoot, home); + const layers = []; + const contributions = []; // [layer name, [[parts, value]], dotted keys whose value was invalid] + const prose = []; + const proseText = {}; + + // pairsOf(fail) returns the layer's accepted [parts, value] pairs; falsy when it contributes none. + const take = (layer, pairsOf) => { + const invalid = new Set(); + const fail = (message, key, valueFailed = false) => { + recordOn(layer, message, key); + if (valueFailed) invalid.add(key); + }; + if (pairsOf) contributions.push([layer.name, pairsOf(fail), invalid]); + layers.push(layer); + }; + const fileLeaves = (data, allowTeamOnly) => data && ((fail) => leaves(data, schema, { teamOnly: only, allowTeamOnly, fail })); + + const shaped = (name, given) => { + if (given === undefined || given === null) return { layer: newLayer(name, null, "absent"), ok: false }; + if (isMapping(given)) return { layer: newLayer(name, null, "loaded"), ok: true }; + return { layer: newLayer(name, null, "invalid", [`${name}: expected a mapping, got ${show(given)}`]), ok: false }; + }; + const d = shaped("defaults", defaults); + take(d.layer, d.ok && fileLeaves(defaults, true)); + const u = shaped("userConfig", userConfig); + take(u.layer, u.ok && ((fail) => userConfigLeaves(userConfig, names, only, fail))); + for (const [name, stem] of stems) { + if (homeEscapes) { + take(escapedLayer(name, stem, homeDir)); + continue; + } + const read = readLayer(name, stem); + take(read.layer, fileLeaves(read.data, name === "team")); + if (read.prose) { + prose.push(read.prose); + proseText[name] = readText(read.prose); + } + } + + const merged = new Map(); // dotted -> {parts, value, from} + let base = new Map(); // the defaults layer's entries, where an invalid higher value falls back to + const within = (dotted, key) => dotted === key || dotted.startsWith(`${key}.`); + for (const [name, pairs, invalid] of contributions) { + // A lower layer's value is never used for an invalid one; the personal override refines the team file, so its keys fall to team. + if (name !== "local") { + for (const key of invalid) { + for (const dotted of [...merged.keys()]) if (within(dotted, key)) merged.delete(dotted); + for (const [dotted, entry] of base) if (within(dotted, key)) merged.set(dotted, entry); + } + } + const layer = layers.find((l) => l.name === name); + for (const [parts, value] of pairs) { + const dotted = parts.join("."); + const prior = merged.get(dotted); + const floor = floorMap.get(dotted); + const union = parts.at(-1) === "disable" && Array.isArray(value); + if (name === "local" && floor && floor.direction !== "no-floor" && !union && prior && [prior.from].flat().includes("team")) { + const why = looser(floor, value, prior.value, nodeAt(schema, parts)); + if (why) { + record(layer, `local (${layer.path}): ${quote(dotted)}: loosens the ${floor.direction} policy floor: ${why}`, dotted); + continue; + } + } + if (union) { + const items = Array.isArray(prior?.value) ? [...prior.value] : []; + const seen = new Set(items.map((i) => JSON.stringify(i))); + for (const item of value) { + const key = JSON.stringify(item); + if (!seen.has(key)) items.push(item); + seen.add(key); + } + // An empty list adds nothing, so its layer is credited only when no layer set the key before. + const from = Array.isArray(prior?.from) ? prior.from : []; + merged.set(dotted, { parts, value: items, from: value.length > 0 || !prior ? [...from, name] : from }); + } else merged.set(dotted, { parts, value, from: name }); + } + if (name === "defaults") base = new Map(merged); + } + const values = {}; + const provenance = {}; + for (const [dotted, { parts, value, from }] of merged) { + setPath(values, parts, value); + put(provenance, dotted, from); + } + + const legacy = legacyOf(plugin, userHome, projectRoot, !homeEscapes && `${join(homeDir, plugin)}.md`); + const sections = mergeSections(proseText.team ?? null, proseText.local ?? null).map(({ heading, text, layer }) => ({ heading, text, layer })); + return { values, provenance, prose, sections, layers, legacy }; +} + +/** The legacy locations that exist; `teamMd` (or false) is the team .md checked for a fenced config block. */ +function legacyOf(plugin, userHome, projectRoot, teamMd) { + const found = [ + ...legacyFiles(join(userHome, ".claude"), plugin, () => "claude-user"), + ...(projectRoot ? legacyFiles(join(projectRoot, ".claude"), plugin, (n) => (n.startsWith(`${plugin}.local.`) ? "claude-local" : "claude-project")) : []), + ...(teamMd && hasConfigBlock(teamMd) ? [{ path: teamMd, kind: "fenced-block" }] : []), + ]; + // The project root may be the user home, so a file is reported under its first kind only. + return found.filter((entry, i) => found.findIndex((e) => e.path === entry.path) === i); +} + +/** + * Each layer's own accepted values, unmerged, for a caller that weighs the layers itself (the + * rendered-views publish rule reads every layer separately: lib/view-settings.mjs). The same reader, + * refusals and schema check as resolve(), with no precedence, floors or invalid-value fallback: an + * invalid value leaves only its own layer. Layers: "userConfig", then "team" and "local" when + * projectRoot is set. `team`, as {path, text}, replaces the working-tree team file (text null: + * absent), for a caller reading it from a git ref. + * readLayers({plugin, projectRoot, home, schema, userConfig, teamOnly, team, userHome}) + * -> {layers: [{name, path, state, errors, error_keys, values: {"a.b": value}}], legacy} + */ +export function readLayers({ plugin, projectRoot = null, home = "docs/conventions", schema, userConfig, teamOnly = [], team, userHome = homedir() }) { + checkPlugin(plugin); + const only = new Set(teamOnly); + const layers = []; + const add = (layer, pairsOf) => { + const values = {}; + for (const [parts, value] of pairsOf ? pairsOf((message, key) => recordOn(layer, message, key)) : []) put(values, parts.join("."), value); + layers.push({ ...layer, values }); + }; + if (isMapping(userConfig)) add(newLayer("userConfig", null, "loaded"), (fail) => userConfigLeaves(userConfig, flatNames(schema, only), only, fail)); + if (!projectRoot) return { layers, legacy: legacyOf(plugin, userHome, null, false) }; + const { homeDir, homeEscapes, stems } = fileLayersOf(plugin, projectRoot, home); + for (const [name, stem] of stems) { + const fileLeaves = (data) => data && ((fail) => leaves(data, schema, { teamOnly: only, allowTeamOnly: name === "team", fail })); + if (name === "team" && team) { + const layer = newLayer(name, team.path, "absent"); + add(layer, typeof team.text === "string" && fileLeaves(parseInto(layer, () => team.text))); + } else if (homeEscapes) { + add(escapedLayer(name, stem, homeDir)); + } else { + const read = readLayer(name, stem); + add(read.layer, fileLeaves(read.data)); + } + } + return { layers, legacy: legacyOf(plugin, userHome, projectRoot, !homeEscapes && `${join(homeDir, plugin)}.md`) }; +} diff --git a/plugins/formal-verification/lib/prerequisites.mjs b/plugins/formal-verification/lib/prerequisites.mjs new file mode 100755 index 00000000000..e451c88aece --- /dev/null +++ b/plugins/formal-verification/lib/prerequisites.mjs @@ -0,0 +1,745 @@ +#!/usr/bin/env node +// GENERATED from lib/prerequisites.mjs by scripts/sync-shared-copies.sh. Do not edit this copy: +// edit the canonical source, then rerun the script. +// Read a plugin's prerequisites.json and report which declared dependencies resolve. +// The contract is docs/contracts/prerequisites/README.md; the schema sits beside it. +// +// prerequisites.mjs report --plugin-root [--plugin-root ...] +// prerequisites.mjs check [--for ] [--data-dir ] +// prerequisites.mjs probe [--run-if-unset-or-true