Agent skill

Proptest Invariant

by joaquinbejar in joaquinbejar/OrderBook-rs

Generate a proptest block for a named orderbook-rs matching-engine invariant.

MITAuto-check: notes

Install Proptest Invariant

skills CLI
$ npx skills add joaquinbejar/OrderBook-rs --skill proptest-invariant -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install joaquinbejar/OrderBook-rs proptest-invariant --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/joaquinbejar/OrderBook-rs.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/proptest-invariant .claude/skills/proptest-invariant && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
proptest-invariant
GitHub stars
543
Token cost
~2.8k tokens
SKILL.md length
796 words
Files
1
Skills in repo
3
Repo updated
First seen
Licence
MIT

At a glance

Generate a proptest block for a named orderbook-rs matching-engine invariant.

  • Works in 7 steps: File placement → Template — the stream strategy → Template — an invariant test → …
  • Adding coverage for invariants like sum of resting quantity conserved
  • SKILL.md covers When to invoke, Supported invariants (lookup… and Procedure
  • Calls cargo and rg

What it does

Proptest Invariant is an agent skill from joaquinbejar/OrderBook-rs. Generate a proptest block for a named orderbook-rs matching-engine invariant. Use when adding coverage for invariants like "sum of resting quantity conserved", "maker.price == trade.price", "no trades with equal maker and taker under STP", "replay byte-identical via the sequencer", "price-time priority never violated", "no orders at zero quantity", or "snapshot restore round-trips". Generates strategies that go through the validated pricelevel newtypes (Price, Quantity, Id, Side, TimeInForce) and drives…

Its SKILL.md is about 2.8k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It works with Rust. The repository describes itself as: A high-performance, thread-safe limit order book implementation written in Rust. This project provides a comprehensive order matching engine designed for low-latency trading… The licence is MIT.

When your agent uses it

  • Adding coverage for invariants like sum of resting quantity conserved
  • Maker.price == trade.price
  • No trades with equal maker and taker under STP
  • Replay byte-identical via the sequencer

Example prompts

  • “sum of resting quantity conserved”
  • “maker.price == trade.price”
  • “no trades with equal maker and taker under STP”
  • “/proptest-invariant”

Requirements

  • Pre-approved tools (allowed-tools): Read, Write, Edit, Grep, Glob, Bash

Workflow steps

7 steps, taken from the step headings in SKILL.md.

  1. File placement
  2. Template — the stream strategy
  3. Template — an invariant test
  4. Invariant-specific hints
  5. Config
  6. After writing
  7. Feature gating

What it can do on your machine

Read from SKILL.md and the folder at commit 54df8eb. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit
    • Grep
    • Glob
    • Bash

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • cargo
    • rg

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Proptest Invariant loads about 2.8k tokens when it runs. Until then it costs about 173 tokens; SKILL.md has 796 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~173
When it runs · the whole SKILL.md, loaded when a task matches
~2.8k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check: notes

The automated check noted patterns worth knowing about, such as sudo or a known installer.

  • NotePre-approves every shell command (allowed-tools: Bash)SKILL.md
    allowed-tools: Read, Write, Edit, Grep, Glob, Bash

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from joaquinbejar/OrderBook-rs at commit 54df8eb, republished under its MIT licence (© joaquinbejar). 796 words, ~2,751 tokens.

Download SKILL.mdSave it as .claude/skills/proptest-invariant/SKILL.md (or your agent's skills folder).
name
proptest-invariant
description
Generate a proptest block for a named orderbook-rs matching-engine invariant. Use when adding coverage for invariants like "sum of resting quantity conserved", "maker.price == trade.price", "no trades with equal maker and taker under STP", "replay byte-identical via the sequencer", "price-time priority never violated", "no orders at zero quantity", or "snapshot restore round-trips". Generates strategies that go through the validated `pricelevel` newtypes (`Price`, `Quantity`, `Id`, `Side`, `TimeInForce`) and drives `OrderBook<T>` via the public `operations` / `modifications` / `mass_cancel` surface. Includes shrinking configuration tuned for short failing streams.
allowed-tools
Read, Write, Edit, Grep, Glob, Bash

Skill: proptest-invariant

Generates a proptest block that targets a specific orderbook-rs matching-engine invariant. The harness drives OrderBook<T> with a randomly generated, valid input stream and asserts the invariant on the resulting state and emitted events.

When to invoke

  • Adding coverage for an invariant that currently has only example tests (or none).
  • User says "property test for <invariant>", "proptest <invariant>", "add a proptest that <property holds>".
  • After changing matching semantics, STP modes, fees, or the sequencer replay path — invariants should regrow coverage.

Supported invariants (lookup table)

NameShape
qty_conservedsum of resting qty on each side invariant under non-matching ops
no_zero_qty_levelsno resting order with Quantity::ZERO, no level with total qty zero
trade_has_one_maker_takerevery TradeEvent has 1 maker + 1 taker, maker.price == trade.price
price_time_priorityfills consume older orders first within a price level
stp_never_self_fillsno TradeEvent where maker and taker share the same owner id
replay_snapshots_matchsequencer replay produces snapshots_match == true
bbo_matches_bookPriceLevelCache top-of-book reflects the actual best bid/ask
fees_per_fill_sumtotal fee across fills equals sum of per-fill fees, no rounding drift
snapshot_restore_roundtriprestore_from_snapshot_package reproduces equivalent state

If the user asks for something not on this list, ask them to name which invariant and where it lives in the public README or lib.rs; then add a row to the table in the same commit as the test.

Procedure

1. File placement
  • Integration tests live at tests/unit/props_<invariant>.rs (one file per invariant group). They are driven via the public OrderBook<T> API only — no crate-internal imports.
  • Shared input-stream strategies live at tests/unit/common/strategies.rs.
  • Unit-level invariants that need crate-internal visibility go under src/orderbook/tests/props_<invariant>.rs gated by #[cfg(test)].

Prefer the integration-test location when the public API covers the invariant; proptest integration tests run under cargo nextest run --test props_<invariant> in isolation, which makes shrink failures easier to reproduce.

2. Template — the stream strategy

Reusable generator for a sequence of valid operations. Biased to produce crossings often enough to exercise matching, not uniformly random.

rust
// tests/unit/common/strategies.rs

use orderbook_rs::prelude::*;
use proptest::prelude::*;
use proptest::collection::vec;

/// Small, deterministic set of owner ids. Keeping the pool small makes STP / self-cross
/// exercise frequently on short streams.
const OWNER_POOL: [u64; 4] = [1, 2, 3, 4];

/// Operation generated by the strategy. Keep this enum local to the test crate so it
/// does not get re-exported by accident.
#[derive(Clone, Debug)]
pub enum Op {
    Submit {
        id: Id,
        owner: u64,
        side: Side,
        price: Price,
        qty: Quantity,
        tif: TimeInForce,
    },
    CancelById(Id),
    MassCancelBySide(Side),
}

pub fn op_stream(len_range: std::ops::Range<usize>) -> impl Strategy<Value = Vec<Op>> {
    vec(op(), len_range)
}

fn op() -> impl Strategy<Value = Op> {
    prop_oneof![
        7 => submit(),
        2 => cancel(),
        1 => mass_cancel(),
    ]
}

fn submit() -> impl Strategy<Value = Op> {
    (
        any::<u64>().prop_map(Id::from_u64),
        any::<usize>().prop_map(|i| OWNER_POOL[i % OWNER_POOL.len()]),
        any::<Side>(),
        // Tight price band forces crossings. A wide uniform range produces a flat empty
        // book that never exercises matching.
        (99u64..=101).prop_map(|t| Price::from_u64(t)),
        (1u64..=100).prop_map(|q| Quantity::from_u64(q)),
        tif_any(),
    )
        .prop_map(|(id, owner, side, price, qty, tif)| Op::Submit {
            id, owner, side, price, qty, tif,
        })
}

fn cancel() -> impl Strategy<Value = Op> {
    any::<u64>().prop_map(|v| Op::CancelById(Id::from_u64(v)))
}

fn mass_cancel() -> impl Strategy<Value = Op> {
    prop_oneof![
        Just(Op::MassCancelBySide(Side::Buy)),
        Just(Op::MassCancelBySide(Side::Sell)),
    ]
}

fn tif_any() -> impl Strategy<Value = TimeInForce> {
    prop_oneof![
        Just(TimeInForce::Gtc),
        Just(TimeInForce::Ioc),
        Just(TimeInForce::Fok),
        Just(TimeInForce::PostOnly),
    ]
}

Key points:

  • Bias weights (prop_oneof![7 => …, 2 => …]) matter. Uniform random rarely exercises cancels or STP paths in a short run.
  • Tight price band forces crossings. Uniform prices over the full range produce a flat empty book.
  • Small owner pool makes self-crosses frequent enough to exercise every STP mode.
  • Strategy only emits values that pass through the validated constructors (Price, Quantity) — invalid inputs belong in their own test.
3. Template — an invariant test

Example for qty_conserved (replace <OrderBookCtor> with the exact constructor used in the project, typically OrderBook::<()>::new("TEST") or a preset builder):

rust
// tests/unit/props_qty_conserved.rs

mod common;
use common::strategies::{op_stream, Op};

use orderbook_rs::prelude::*;
use proptest::prelude::*;

fn apply(book: &OrderBook<()>, op: &Op) {
    match op {
        Op::Submit { id, owner, side, price, qty, tif } => {
            let _ = book.submit_limit(*id, *owner, *side, *price, *qty, *tif);
        }
        Op::CancelById(id) => {
            let _ = book.cancel(*id);
        }
        Op::MassCancelBySide(side) => {
            let _ = book.mass_cancel_by_side(*side);
        }
    }
}

fn bid_qty_sum(book: &OrderBook<()>) -> u64 {
    book.iter_levels(Side::Buy)
        .map(|lvl| lvl.total_quantity().as_u64())
        .sum()
}

fn ask_qty_sum(book: &OrderBook<()>) -> u64 {
    book.iter_levels(Side::Sell)
        .map(|lvl| lvl.total_quantity().as_u64())
        .sum()
}

proptest! {
    #![proptest_config(ProptestConfig {
        cases: 256,
        max_shrink_iters: 50_000,
        ..ProptestConfig::default()
    })]

    #[test]
    fn qty_conserved_across_snapshot(stream in op_stream(1..200)) {
        let book = OrderBook::<()>::new("TEST");
        for op in &stream { apply(&book, op); }

        let bid_before = bid_qty_sum(&book);
        let ask_before = ask_qty_sum(&book);

        // Non-matching op: snapshot must not change resting qty.
        let _snap = book.snapshot();

        prop_assert_eq!(bid_qty_sum(&book), bid_before);
        prop_assert_eq!(ask_qty_sum(&book), ask_before);
    }
}

Adjust OrderBook::<()>::new("TEST") to whichever constructor form the project actually exposes at the time the skill runs; verify with rg -n 'impl<.*> OrderBook' src/orderbook/book.rs.

Show full SKILL.md (369 more words)Show less
4. Invariant-specific hints
  • trade_has_one_maker_taker — register a TradeListener, collect TradeEvents into a Vec, then assert each has distinct maker_order_id / taker_order_id and that trade.price == maker_resting_price (snapshot the maker price before the fill).
  • stp_never_self_fills — configure the book with one of the active STP modes, then filter the trade-event vec for maker.owner == taker.owner; assert it is empty for every mode under test.
  • price_time_priority — assert that within each price level, the order with the earlier TimestampMs fills first. Walk the trade vec by price level and compare maker timestamps.
  • replay_snapshots_match — run the sequencer with the in-memory journal, replay into a fresh book, call snapshots_match(&live, &replayed) and assert true. The sequencer's snapshots_match is already the canonical oracle; the proptest just widens coverage beyond the fixed streams in tests/unit/.
  • bbo_matches_book — after applying the stream, compare book.best_bid() / book.best_ask() against the first element of book.iter_levels(side).
  • fees_per_fill_sum — configure a FeeSchedule, sum per-fill fee_paid values from every TradeEvent, compare to the TradeResult aggregate — assert exact equality (integer fee model).
  • snapshot_restore_roundtrip — let pkg = book.snapshot_package(); → build a fresh book → restored.restore_from_snapshot_package(pkg) → assert structural equality of price levels, cache, STP mode, fee schedule.
5. Config
  • cases: 256 by default. Bump to 1024+ for a nightly / release job, not for the default cargo nextest run.
  • max_shrink_iters: 50_000 — matching bugs often need aggressive shrinking to reach a minimal failing stream; the proptest default of 1024 is too low.
  • Persist regressions: proptest writes failing inputs to proptest-regressions/. Commit that directory — it's the first line of defense against regressions of the same shape.
6. After writing
  • cargo nextest run --test props_<invariant> (or cargo test --test props_<invariant> -- --nocapture if nextest is unavailable).
  • If the test flakes or the shrink doesn't converge, inspect the strategy first — usually the price band is too wide, the owner pool too large, or the TimeInForce mix missing PostOnly.
  • Commit with a conventional prefix: test(orderbook): proptest for <invariant>.
7. Feature gating
  • Invariants that exercise repricing.rs (pegged / trailing-stop) must be gated: #[cfg(feature = "special_orders")] on the test function and matching CI job.
  • Invariants that exercise NATS publishing should be gated on feature = "nats" and mark them #[ignore] by default; they are integration tests against a running server.
  • Journal-replay invariants work under default features; the journal feature only adds the file-backed journal (the in-memory journal is always available).

© joaquinbejar, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .agents/skills/proptest-invariant of joaquinbejar/OrderBook-rs.

Open the folder on GitHubat commit 54df8eb

Compare with similar skills

Proptest Invariant next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Proptest Invariant compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Proptest Invariant this skilljoaquinbejar/OrderBook-rs543—~2.8kAutomated safety check: NotesMIT
Update V8 Versionopeninterpreter/openinterpreter69k2 repos~845Automated safety check: PassApache-2.0
Firecrawl Page Scrape Integrationfirecrawl/firecrawl190k1 repos~944Automated safety check: PassISC
Migrate Core Code to Submodulestinyhumansai/openhuman42k—~2.6kAutomated safety check: PassGPL-3.0
Rust TDD Workflowrtk-ai/rtk83k—~753Automated safety check: NotesApache-2.0
OpenLogi macOS Permissions TriageAprilNEA/OpenLogi23k—~2.5kAutomated safety check: NotesApache-2.0

Similar skills

  • Update V8 Version

    openinterpreter/openinterpreter

    Bumps the pinned v8 and rusty_v8 versions in Codex, validates the release-candidate path with the v8-canary check, and traces failures to upstream build changes.

    69k GitHub starsUsed in 2 repos~845 tokens
    DevOps & CloudAuto-check passed
  • Adds Firecrawl's /scrape endpoint to application code to pull markdown, HTML, links, screenshots or structured data from a single known URL.

    190k GitHub starsUsed in 1 repo~944 tokens
    Data & AnalyticsAuto-check passed
  • Migrate Core Code to Submodules

    tinyhumansai/openhuman

    Plans and carries out moving non-host-specific code and its tests from the OpenHuman core into vendored tiny submodule libraries, then releases the submodule and re-pins the host.

    42k GitHub stars~2.6k tokensUpdated today
    DevelopmentAuto-check passed
  • Enforces red-green-refactor for Rust work, with idiomatic test patterns, a naming convention and a pre-commit gate of cargo fmt, clippy and test.

    83k GitHub stars~753 tokensUpdated today
    Testing & QAAuto-check: notes
  • Decides whether an OpenLogi device problem on macOS is a privacy-permission (TCC) problem, using agent log lines, and says which identity needs which grant.

    23k GitHub stars~2.5k tokensUpdated today
    DevelopmentAuto-check: notes
  • Guide for writing idiomatic Rust code based on Apollo GraphQL's best practices handbook.

    5.6k GitHub starsUsed in 3 repos~1.1k tokens
    DevelopmentAuto-check passed

More from joaquinbejar/OrderBook-rs

  • Bench Hdr

    joaquinbejar/OrderBook-rs

    Add or update an orderbook-rs hot-path latency benchmark that reports p50 / p99 / p99.9 / p99.99 via hdrhistogram, not the criterion default mean.

    543 GitHub stars~2.9k tokensUpdated 5 days ago
    Auto-check: notes
  • Source Command Implement Roadmap

    joaquinbejar/OrderBook-rs

    Autonomously implement every roadmap issue end-to-end (PR → Copilot review → respond → green CI → merge → roadmap update) until done

    543 GitHub stars~4.2k tokensUpdated 5 days ago
    Auto-check passed

Works with

Questions about Proptest Invariant

What does Proptest Invariant do?

Generate a proptest block for a named orderbook-rs matching-engine invariant. Proptest Invariant is an agent skill from joaquinbejar/OrderBook-rs. Generate a proptest block for a named orderbook-rs matching-engine invariant.

When should I use Proptest Invariant?

Proptest Invariant fits situations like: adding coverage for invariants like sum of resting quantity conserved; maker.price == trade.price; no trades with equal maker and taker under STP; replay byte-identical via the sequencer.

How do I install Proptest Invariant in Claude Code?

Run `npx skills add joaquinbejar/OrderBook-rs --skill proptest-invariant -a claude-code`. Or copy the skill folder (.agents/skills/proptest-invariant in joaquinbejar/OrderBook-rs) into .claude/skills/proptest-invariant in your project. Claude Code loads it when a task matches its description.

How do I install Proptest Invariant in Codex?

Run `npx skills add joaquinbejar/OrderBook-rs --skill proptest-invariant -a codex`. Or copy the skill folder (.agents/skills/proptest-invariant in joaquinbejar/OrderBook-rs) into .agents/skills/proptest-invariant in your project. Codex loads it when a task matches its description.

Can I use Proptest Invariant in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add joaquinbejar/OrderBook-rs --skill proptest-invariant -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/proptest-invariant, .gemini/skills/proptest-invariant, .github/skills/proptest-invariant and .opencode/skills/proptest-invariant in your project.

What does Proptest Invariant need to run?

Going by SKILL.md and its folder, Proptest Invariant needs the command-line tools its instructions call (cargo and rg). Its frontmatter pre-approves these tools: Read, Write, Edit, Grep, Glob, Bash.

Does Proptest Invariant access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Proptest Invariant safe to install?

Our automated static check of SKILL.md found notes only (pre-approves every shell command (allowed-tools: bash)), nothing it rates as a warning. It is not a guarantee. Review the folder before installing.

What licence does Proptest Invariant use?

Proptest Invariant is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Proptest Invariant use?

About 2.8k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Proptest Invariant?

Skills that share tags, products or a category with Proptest Invariant: Update V8 Version (openinterpreter/openinterpreter, 69k stars), Firecrawl Page Scrape Integration (firecrawl/firecrawl, 190k stars), Migrate Core Code to Submodules (tinyhumansai/openhuman, 42k stars) and Rust TDD Workflow (rtk-ai/rtk, 83k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Proptest Invariant?

joaquinbejar (a GitHub user) maintains it in joaquinbejar/OrderBook-rs, which has 543 GitHub stars. The repository holds 3 skills in this directory. The repository was last updated on October 5, 2026.

Source: joaquinbejar/OrderBook-rs on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.