A plugin shapes how diffr shows a changed file. Every plugin implements the
same contract, wit/plugin.wit, and diffr loads and
runs every plugin the same way: the bundled ones (plugins/<name>/, compiled
into diffr) and WASM components in a folder the configuration points at. All
are configured the same way, in [plugins] (config.md),
and produce the same wire records (streaming.md).
This is a research prototype: a WASM plugin runs with full access to the machine (see Access). Run only plugins you trust.
A plugin is made once, then a file passes three points, each in
plugins.order:
- New. When diffr starts, before any output, it makes each enabled
plugin's one instance for the run: it deserializes the plugin's options
into the plugin's own options type and calls
newwith them. A plugin that cannot be made (options that do not deserialize, a summarizer without an API key, a component that does not compile or link) is a setup error: diffr writes it to stderr, naming its bundled or external config entry, and exits 2 before any record, for native and component plugins alike. - Pre-process:
classify. Before the stream starts, each plugin'sclassifyreturns tags to add to the file's manifest entry. They join the tags from the bundled rules and git attributes (config.md), so they decide how the file is diffed (ageneratedfile gets a line diff), how--orderranks it, and what later plugins see: each plugin sees the tags the ones before it added. An error here, or a tag that is not lowercase letters, digits,-and_, is a setup error. - During: queries. The named tree-sitter source text returned by a
plugin's
queries()joins the per-language fold query the diff runs with (config.md). They decide which folds exist and tag them<plugin>:<name>. diffr collects and validates the sources once during setup, before the stream starts. Tags are the only syntax a plugin sees: thecontextplugin reads the scopes its queries tagcontext:scope. - Post-process:
mutate. After the file is diffed and its region trees are built, each plugin'smutatereads the file and both sides and returns moves, which diffr carries out before the next plugin runs. An error, a trap, or a move that cannot be carried out aborts the run withmutation_failednaming the plugin.
examples/plugins/fixtures/
plugin.toml # name, title, options schema
plugin.wasm # the component
queries/rust.scm # optional: one query file per language
plugin.toml is the same file the bundled plugins carry
(config.md): name (the entry name in
[plugins], and the prefix of every tag its queries set), title,
description, [enabled] (with default, whether the plugin is on unless
its entry says otherwise), [options.<key>] (each a JSON Schema with a
title). Query sources belong to the plugin's code, typically embedded
with include_str!, and are returned by queries(); there is no [queries]
manifest section. See query sources and imports.
An external plugin is explicitly selected in the user's config:
[plugins]
order = ["bundled.context", "external.fixtures", "bundled.group"]
[plugins.external.fixtures]
path = "plugins/fixtures"
fail = falseThe path is relative to the config file's directory, or absolute. The folder's
manifest must name fixtures, and plugin.wasm must exist when the plugin
is loaded. A missing component is an error even if a native plugin has the
same name. Plugins keep their unqualified names and tag prefixes regardless
of whether they are loaded through bundled or external.
Bundled plugins use their registered implementations; external plugins use the WASM interface. Config controls enabled state, options and order. An explicit order does not silently add other bundled plugins. Adding an external plugin never requires rebuilding diffr.
wit/plugin.wit is the contract: the package
diffr:plugin@0.1.0, world plugin. A plugin exports the interface guest,
which holds one resource, the plugin itself (the component model has no
optional exports; a plugin that does not classify returns an empty list):
resource plugin {
new: static func(options: string) -> result<plugin, string>;
queries: func() -> result<list<query-source>, string>;
classify: func(file: file-entry) -> result<list<string>, string>;
mutate: func(file: file-entry, sides: source-sides) -> result<list<move>, string>;
}new is a static function rather than a constructor, because a constructor
cannot fail. queries returns records with language, name, and text
strings; the Rust SDK defaults to an empty list. Existing WASM components
must be rebuilt to provide the new export.
options: the plugin's entry as a JSON object, defaults filled in and already validated againstplugin.toml. Onlynewgets it; what the plugin keeps from it lasts the run.file-entry:file,statusandtags.fileis the manifest entry's sides —both,left-only(a deletion) orright-only(an addition) — and each side is afile-refofpath,oid(the blob; empty outside a repository) andmode.statussays how the two sides relate, which the sides alone do not: a path that changed isrenamed, an object kind that changedtype-changed. The SDK'sFileEntry::side()is the side a file is named by andpath()its path.source-sides: the sides the diffed file has, shaped likefile-sides. The SDK rebuilds them as trees on the way in, so a plugin'smutateis handed aPairing<Source>rather than the flat records.source: one side'stextand itsregions, the tree flattened in preorder: eachregioncarries itsparent(a fold'sid, or0for a top-level region),id,fold-state-id,range,tags,visibility, andkind:leaf(alignment-id, changed)orfold. The fields mean what they mean on the wire (streaming.md). A binary file's sides have empty text and no regions.move:cut({region, at}),join-folds(ids),link-fold-state(ids),set-collapsed((id, collapsed)),set-label((id, label))andset-tags((id, tags)), with the semantics of the moves in streaming.md.0names the file where a move allows it.
diffr builds these records once per call, from the file's manifest entry and its trees as the plugins before left them, and hands the same records to a native plugin and to a component. Nothing else reaches a plugin.
diffr makes one instance of each plugin per run and calls it for every file.
A native plugin's instance is called from several files' workers in parallel,
so it must be Send + Sync; interior mutability is the plugin's own
business. A component's instance lives in one wasmtime store, which runs one
call at a time: diffr calls a component plugin one file at a time.
A plugin often needs to name what its own moves create: the piece a cut leaves, the fold a join adds. Ids are handed out deterministically, so a plugin can predict them:
- When a plugin's moves begin, the next fresh
idis one above the largest regionidin the file (both sides), and the next freshalignment_idone above the largest leafalignment_id. - A cut takes one fresh
alignment_id, which the second pieces share, then one freshidfor the second piece on each side that holds the leaf or the leaf paired with it, lhs first. Both second pieces take the lhs piece'sid(or the only piece's) as theirfold_state_id. The first piece keeps the leaf's ids. - A join takes one fresh
idfor the new fold on each side that holds the listed regions, lhs first; both share the lhs fold'sidas theirfold_state_id. - No other move takes an id.
So cutting a paired leaf when the largest id is n names the lhs piece
n + 1 and the rhs piece n + 2. diffr carries out every plugin's moves
with the SDK's applier (crates/diffr-plugin-sdk/src/apply.rs), the same
code a plugin predicts ids with.
Besides WASI, which only a component gets, diffr gives every plugin one
import, diffr:plugin/host:
git(args) -> result<string, string>: runsgitwith these arguments in the repository's working directory (the current directory for--no-index), returning stdout on success and stderr otherwise.
A host failure (git cannot be started, or its output is not UTF-8) is the call's error, natively and in a component alike.
A plugin does everything else itself. It reads files: a component has the
working directory preopened, and reads any side of a file the working tree
does not have with git show. And it prints what it wants to say to stderr,
rather than calling diffr to say it.
A component gets full access; diffr does not sandbox it:
- WASI with the working directory preopened read-write as
.. - The environment inherited.
- The network open, with name lookup and standard WASI HTTP/HTTPS outgoing requests.
- Its stdout and stderr captured, and written to diffr's stderr a line at a
time, each line prefixed with
[<plugin name>]. Neither may reach diffr's stdout, which is the stream. A native plugin writes to diffr's stderr directly, and is not prefixed.
crates/diffr-plugin-sdk is the contract in Rust, and every bundled plugin is
written with it:
types: the contract's records, generated fromwit/plugin.wititself bywit_bindgen::generate!, so there is one definition of each. A plugin works with the same records natively and as a component.Plugin: the one trait, mirroring thepluginresource. A plugin is a struct with anOptionstype (deserialized from the options JSON), and implementsnew(make the plugin from its options; where it can fail),queries,classifyandmutate.queriesdefaults to an empty list; a plugin that does not classify returnsOk(Vec::new()).export!("my-plugin", MyPlugin): built forwasm32, exports the plugin as the component'spluginresource: itsnewdeserializes the options string intoOptionsand callsPlugin::new, and itsclassifyandmutatecall the instance with the records it was given, since the guest bindings' records are the contract's. Built for a native target, it exposes the name and constructor asDIFFR_PLUGIN, collected into diffr's registry at build time. The native registry deserializes the options and calls the trait itself. The same source builds both ways.host::git: the host function, the same call natively and in a component.tree::sidesrebuilds the contract's sides as region trees (Pairing<Source>, eachRegionholding its children). The SDK calls it itself, somutatereceives the trees; the module also holds the helpers the bundled plugins read them with:walk,OtherSide,one_sided,docstring_of,before_and_after_ids, and the rest.Draftcarries moves out on a copy of the trees as the plugin makes them, with diffr's applier, sodraft.cut_lines,draft.collapse,draft.linkanddraft.groupcan name what earlier moves created.apply::Fresh::of(&sides)predicts ids without a draft.
# Cargo.toml
[dependencies]
diffr-plugin-sdk = { path = "../../../crates/diffr-plugin-sdk" }
serde = { version = "1.0", features = ["derive"] }use diffr_plugin_sdk::{anyhow, export, FileEntry, Move, Pairing, Plugin, Source, ROOT};
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Options {}
pub struct HideAll;
impl Plugin for HideAll {
type Options = Options;
fn new(_: Options) -> anyhow::Result<Self> {
Ok(Self)
}
fn classify(&self, _: &FileEntry) -> anyhow::Result<Vec<String>> {
Ok(Vec::new())
}
fn mutate(&self, _: &FileEntry, _: &Pairing<Source>) -> anyhow::Result<Vec<Move>> {
Ok(vec![Move::SetCollapsed((ROOT, true))])
}
}
export!("hide-all", HideAll);Build it as a component with the pinned toolchain and the wasm32-wasip2
target, which emits a component directly:
rustup target add wasm32-wasip2
cargo rustc --release --target wasm32-wasip2 --crate-type cdylib
cp target/wasm32-wasip2/release/hide_all.wasm plugin.wasmcargo xtask build-plugins builds every plugin crate in this repository
that runs as a component into its folder's plugin.wasm. The bundled
summarizer's component is committed because normal builds embed it without
requiring a WASM toolchain; rebuild and commit it whenever its source, manifest,
queries or SDK changes. Other plugin build outputs are not committed.
diffr compiles each component once per run, with wasmtime's
compilation cache on disk, so an unchanged component is not recompiled on the
next run.
-
examples/plugins/fixtures:classifytags a filefixturewhen it is under afixtures/directory or its first line is// fixture(read from the blob the file entry names, withgit cat-file, so a deleted file is read as readily as a new one);mutatehides a fixture behind the subject of the last commit that touched it (fromgit log -1 --format=%s -- <path>), and collapses all but the first line of its first leaf, naming the cut's piece by predicting its id. Itsfailoption makesmutatereturn an error. -
plugins/context,plugins/hide-files,plugins/deleted-bodies,plugins/test-bodies,plugins/removed-runsandplugins/group: the bundled plugins, which build as components too. Pointing their entries at the bundled folders once the script has built them runs the components in place of the native code, and produces the same stream (tests/wasm.rschecks it, withcargo test --features wasm-plugin-tests --test wasm: the tests build every plugin forwasm32-wasip2, so they are behind a feature and run where that target is installed):[plugins.bundled.deleted-bodies] path = "/path/to/diffr/plugins/deleted-bodies"
-
plugins/summarize: a network-backed component example that runs as WASM even when bundled. Its transport useswasi:http/outgoing-handlerfor HTTP/HTTPS, including request headers, streaming bodies and timeouts. Build it withcargo xtask build-plugins, then load it without rebuilding diffr:[plugins] order = ["external.summarize", "bundled.test-bodies", "bundled.group"] [plugins.external.summarize] path = "/path/to/diffr/plugins/summarize" enabled = true # Reads GEMINI_API_KEY or GOOGLE_API_KEY from the inherited environment.
plugins/summarize/src/http.rsis a complete outgoing-request example for plugin authors. The host provides TLS; components do not need to embed a TLS implementation. WASM instances process files serially; the legacymax_concurrencyoption is accepted but has no effect. Timeouts apply to connection, first-byte and between-byte waits.cargo test --features wasm-plugin-tests --bin diffr external_component_summarizes_over_httpchecks the external component against a local model endpoint, including retries.
Native plugin crates register their name and constructor through the same
export!("name", Type) macro used for WASM exports. The linker gathers the
registrations; configuration still controls instantiation and execution order.
Native crates must be dependencies linked into the host. External WASM plugins
need no native registration and do not require rebuilding diffr.
Repository tooling discovers plugin crates through cargo metadata and
[package.metadata.diffr] in each crate's Cargo.toml. native = true links a
bundled implementation into diffr; otherwise the plugin uses WASM. This does
not add a WASM requirement to cargo install. cargo xtask test-plugins
builds WASM variants and runs parity tests. The workspace's
wasm-test-exclude list can record test-only exceptions; currently all plugins build as WASM.
The host also discovers bundled manifests and query assets from its plugin
dependencies, rather than maintaining a second file list. A dependency marked
native = true contributes its registration; otherwise its prebuilt
plugin.wasm is embedded alongside its manifest. The default configuration
chooses which bundled plugins run; discovering an asset does not enable it.
Enable summarize to get pseudocode for new functions and right-side test
bodies. tests = false disables test summaries independently; test_min_lines
(default 20) controls their size threshold. Modified and unchanged tests in a
diffed file qualify too; deleted tests do not. A summary must fit in half the
body's nonblank lines or the ordinary test fold remains.
The default order runs summarize before test-bodies, then group.
test-bodies preserves existing labels and still collapses modules and bodies.
Opening a module or aggregate fold reveals each test's pseudocode; opening an
individual body reveals its source. JS/TS describe suites remain containers,
with summaries on their individual it/test callbacks. An explicit custom
plugins.order is respected; update it to this order to match the defaults.